C#Owin WebApp:解析POST请求? [英] C# Owin WebApp: Parsing POST Requests?

查看:317
本文介绍了C#Owin WebApp:解析POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在C#控制台应用程序中解析HTTP POST请求。该应用使用Owin运行网络服务器。该应用程序的详细信息可在此处并且相关代码的当前稳定版本为此处

我正在扩展上述应用程序以通过Web UI启用配置。例如,该应用程序目前报告大量的参数。我希望最终用户能够选择通过网络报告哪些参数。为此,我对上面的代码做了一些修改:

使用Microsoft.Owin的

 使用Owin 
;
.........
[汇编:OwinStartup(typeof(SensorMonHTTP.WebIntf))]
.........
... ......
命名空间SensorMonHTTP
{
...
公共类WebIntf
{
公共无效配置(IAppBuilder应用程序)
{
app.Run(context =>
{
var ConfigPath = new Microsoft.Owin.PathString(/ config);
var ConfigApplyPath = new Microsoft.Owin .PathString(/ apply_config);
var SensorPath = new Microsoft.Owin.PathString(/);
if(context.Request.Path == SensorPath)
{
return context.Response.WriteAsync(GetSensorInfo());
/ *返回带有传感器信息的JSON字符串* /
}
else if(context.Request.Path == ConfigPath)
{
/ *动态生成HTML以列出可用传感器
带有复选框的信息使用Dynatree:Tree $ under
'Checkbox&选择'连同代码在
下执行POST'在表单中嵌入'在
中http://wwwendt.de/tech/dynatree/doc/samples.html * /
/ *最终细分生成的HTML如下所示:
< script>
$
$(form)。submit(function(){
var formData = $(this).serializeArray();
var tree = $ (#tree3)。dynatree(getTree);
formData = formData.concat(tree.serializeArray());
// alert(POST this:\\\
+ jQuery。 param(formData));
// - 在测试
$ .post(apply_config,formData);
时返回true;
});
......
< / script>< / head>
< body>
< form action =apply_configmethod =POST>
< input type =submitvalue =记录选定参数>
< div id =tree3name =selNodes>< / div>
< / body>
< / html>
生成的HTML代码结束* /
}
else if(context.Request.Path == ConfigApplyPath)
{
/ *我想访问并解析POST data here * /
/ *尝试将context.Request.Body作为MemoryStream
查看,但没有获取任何数据。 * /
}
}
}
........
}

任何人都可以帮助我了解如何在上面的代码结构中访问POST数据?

预先感谢!

解决方案

由于数据以KeyValuePair格式返回,因此您可以将其转换为IEnumerable,如下所示:

  var formData =等待context.Request.ReadFormAsync()作为IEnumerable< KeyValuePair< string,string []>>; 

//现在您有了可以查询的列表

  var formElementValue = formData.FirstOrDefault(x => x.Key ==NameOfYourHtmlFormElement)。Value [0]); 


I would like some help on parsing HTTP POST requests in a C# console application. The app runs a 'web-server' using Owin. Details of the application are available here and the current 'stable version' of the relevant code is here.

I am extending the above application to enable configuration through the web UI. For example, the app currently reports a large number of parameters. I would like the end-user to be able to select which parameters get reported over the network. Towards this, I made some modifications to the code above:

    using Microsoft.Owin;
    using Owin;
    .........
    [assembly: OwinStartup(typeof(SensorMonHTTP.WebIntf))]
    .........
    .........
    namespace SensorMonHTTP
    {
      ...
      public class WebIntf
      {
        public void Configuration(IAppBuilder app)
        {
          app.Run(context =>
          {
            var ConfigPath = new Microsoft.Owin.PathString("/config");
            var ConfigApplyPath = new Microsoft.Owin.PathString("/apply_config");
            var SensorPath = new Microsoft.Owin.PathString("/");
            if (context.Request.Path == SensorPath) 
            { 
              return context.Response.WriteAsync(GetSensorInfo()); 
              /* Returns JSON string with sensor information */
            }
            else if (context.Request.Path == ConfigPath)
            {
              /* Generate HTML dynamically to list out available sensor 
                 information with checkboxes using Dynatree: Tree3 under 
                 'Checkbox & Select' along with code to do POST under 
                 'Embed in forms' in 
                 http://wwwendt.de/tech/dynatree/doc/samples.html */
              /* Final segment of generated HTML is as below:
              <script>
              .....
              $("form").submit(function() {
                var formData = $(this).serializeArray();
                var tree = $("#tree3").dynatree("getTree");
                formData = formData.concat(tree.serializeArray());
                // alert("POST this:\n" + jQuery.param(formData)); 
                // -- This gave the expected string in an alert when testing out
                $.post("apply_config", formData);
                return true ;
              });
              ......
              </script></head>
              <body>
              <form action="apply_config" method="POST">
              <input type="submit" value="Log Selected Parameters">
              <div id="tree3" name="selNodes"></div>
              </body>
              </html>
              End of generated HTML code */
            }
            else if (context.Request.Path == ConfigApplyPath)
            {
              /* I want to access and parse the POST data here */
              /* Tried looking into context.Request.Body as a MemoryStream, 
                 but not getting any data in it. */
            }
          }
        }
        ........
      }

Can anyone help me with how the POST data can be accessed in the above code structure?

Thanks in advance!

解决方案

Since the data returns in KeyValuePair format you can cast it as IEnumerable which looks something like the following:

var formData = await context.Request.ReadFormAsync() as IEnumerable<KeyValuePair<string, string[]>>;

//now you have the list that you can query against

var formElementValue = formData.FirstOrDefault(x => x.Key == "NameOfYourHtmlFormElement").Value[0]);

这篇关于C#Owin WebApp:解析POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆