首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C# Owin WebApp:解析POST请求?

C# Owin WebApp:解析POST请求?
EN

Stack Overflow用户
提问于 2013-12-14 08:53:30
回答 5查看 10.3K关注 0票数 5

我想要一些在C#控制台应用程序中解析HTTP POST请求的帮助。这个应用使用Owin运行一个'web-server‘。该应用程序的详细信息可从here获得,相关代码的当前“稳定版本”为here

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

代码语言:javascript
复制
    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. */
            }
          }
        }
        ........
      }

有没有人可以帮助我在上面的代码结构中如何访问POST数据?

提前感谢!

EN

回答 5

Stack Overflow用户

发布于 2015-03-17 04:47:23

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

代码语言:javascript
复制
var formData = await context.Request.ReadFormAsync() as IEnumerable<KeyValuePair<string, string[]>>;

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

代码语言:javascript
复制
var formElementValue = formData.FirstOrDefault(x => x.Key == "NameOfYourHtmlFormElement").Value[0]);
票数 11
EN

Stack Overflow用户

发布于 2013-12-16 12:16:09

您可以在IOwinRequest对象上使用ReadFormAsync()实用程序来读取/解析表单参数。

代码语言:javascript
复制
public void Configuration(IAppBuilder app)
        {
            app.Run(async context =>
                {
                    //IF your request method is 'POST' you can use ReadFormAsync() over request to read the form 
                    //parameters
                    var formData = await context.Request.ReadFormAsync();
                    //Do the necessary operation here. 
                    await context.Response.WriteAsync("Hello");
                });
        }
票数 6
EN

Stack Overflow用户

发布于 2018-06-02 04:04:15

要提取每个内容类型的主体参数,可以使用如下方法:

代码语言:javascript
复制
    public async static Task<IDictionary<string, string>> GetBodyParameters(this IOwinRequest request)
    {
        var dictionary = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

        if (request.ContentType != "application/json")
        {
            var formCollectionTask = await request.ReadFormAsync();

            foreach (var pair in formCollectionTask)
            {
                var value = GetJoinedValue(pair.Value);
                dictionary.Add(pair.Key, value);
            }
        }
        else
        {
            using (var stream = new MemoryStream())
            {
                byte[] buffer = new byte[2048]; // read in chunks of 2KB
                int bytesRead;
                while ((bytesRead = request.Body.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }
                var result = Encoding.UTF8.GetString(stream.ToArray());
                // TODO: do something with the result
                var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);

                foreach(var pair in dict)
                {
                    string value = (pair.Value is string) ? Convert.ToString(pair.Value) : JsonConvert.SerializeObject(pair.Value);
                    dictionary.Add(pair.Key, value);
                }
            }
        }

        return dictionary;
    }

    private static string GetJoinedValue(string[] value)
    {
        if (value != null)
            return string.Join(",", value);

        return null;
    }

参考资料:Most efficient way of reading data from a stream

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20578452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档