C#Owin WebApp:解析POST请求?

 手机用户2602927807 发布于 2023-02-10 14:58

我想在C#控制台应用程序中解析HTTP POST请求方面的一些帮助.该应用程序使用Owin运行"网络服务器".此处提供了该应用程序的详细信息,相关代码的当前"稳定版本"在此处.

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

    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:
              
              
              
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数据?

提前致谢!

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

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

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

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

    2023-02-10 15:00 回答
  • 您可以在IOwinRequest对象上使用ReadFormAsync()实用程序来读取/解析表单参数。

    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");
                    });
            }
    

    2023-02-10 15:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有