无法从 POST 请求反序列化 HttpContent

Can not deserialize HttpContent from POST request

我正在尝试将 POST 请求发送到 server.The 请求进入 MiddlewareInvoke 方法。

然而,无论对象的类型如何,Content 始终为 null。

发件人

public async Task<string> RunTestAsync(string request)
{
    try
    {
        var content = new StringContent(JsonConvert.SerializeObject(request),Encoding.UTF8,"application/json");

       var response=await this.client.PostAsync("http://localhost:8500/mat",
                              content);

        string str=await response.Content.ReadAsStringAsync();
        stringdata = JsonConvert.DeserializeObject<string>(str);
        return data;     
    }
    catch (Exception ex)
    {
        Console.WriteLine("Threw in client" + ex.Message);
        throw;
    }
}

服务器

服务器没有定义 service,只有一个响应 route 的普通 middleware。 (请求在 Invoke 方法中获取!)

启动

 public class Startup
   {
        public void ConfigureServices(IServiceCollection services) {

        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

            app.UseDeveloperExceptionPage();
            app.UseBlazor<Client.Startup>();

            app.Map("/mid", a => {
                     a.UseMiddleware<Mware>();
                });
            });
        }
   }

中间件

public class Mware
{
    public RequestDelegate next{get;set;}

    public Mware(RequestDelegate del)
    {
      this.next=del;
    }
    public async Task Invoke(HttpContext context)
    {

            using (var sr = new StreamReader(context.Request.Body))
            {
                string content = await sr.ReadToEndAsync();//null ,tried other types too , still null ,and the ContentLength is null too
                var request=JsonConvert.DeserializeObject<string>(content);
                if (request == null)
                {
                    return;
                }
            }
    }
}

我检查了我的序列化,对象序列化得很好。

尽管如此,我总是在另一边得到 null

P.S

我也试过不使用 middleware 只是一个普通的委托,如下所示:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

        app.UseDeveloperExceptionPage();
        app.UseBlazor<Client.Startup>();

        app.Map("/mid",x=>{
            x.Use(async(context,del)=>{
                using (var sr = new StreamReader(context.Request.Body))
                {
                  string content = await sr.ReadToEndAsync();//null ,tried other types too , still null ,and the ContentLength is null too
                  var request=JsonConvert.DeserializeObject<string>(content);
                  if (request == null)
                  {
                    return;
                  }
                }
        });
    }

即使没有专用的 middleware 问题仍然存在。

问题不在于 middleware,而是在客户端中正确序列化并发送到服务器的请求,并且其 body 以某种方式显示为 null

如果它未能 deserialize 对象,我会理解,但是 HttpContext.Request.Body 作为字符串被接收 null 并且它的 lengthnull !!

在您的示例中,客户端代码调用路由“/mat”,但中间件配置在“/mid”。如果你的代码 运行 有同样的错误,中间件不会被命中,你总是会得到一个空的响应,从客户端看,就像中间件收到 null.确保您也使用了正确的端口号——我的端口号是 :5000,但它可能因运行时配置而异。

您是否使用调试器和断点进行测试?如果没有,我强烈建议尝试。我能够很快找到该错误,因为我在服务器端代码中设置了一个断点,并观察到它没有被击中。如果调试器不是一个选项,请考虑 "failing loudly" 通过抛出异常(而不是简单地返回)来更清楚地表明您是否真的达到了您认为正在达到的条件。

不确定您的代码到底出了什么问题,但这行得通:

public class Startup
{
  // This method gets called by the runtime. Use this method to add services to the container.
  // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  public void ConfigureServices(IServiceCollection services)
  {
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
    if (env.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }

    app.Run(async (context) =>
    {
      var request = context.Request;
      var body = request.Body;

      request.EnableRewind();
      var buffer = new byte[Convert.ToInt32(request.ContentLength)];
      await request.Body.ReadAsync(buffer, 0, buffer.Length);
      var bodyAsText = Encoding.UTF8.GetString(buffer);
      request.Body = body;
      await context.Response.WriteAsync(bodyAsText);
    });
  }
}

运行 这在 chrome 开发工具中:

fetch('http://localhost:39538', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8'
  }
})
.then(res => res.json())
.then(console.log)

在浏览器中产生以下内容:

{"title":"foo","body":"bar","userId":1}

假设您的请求是 request= @" {"title":"foo","body":"bar","userId":1}";

调用 RunTestAsync(请求); 运行 就是这个 JsonConvert.SerializeObject(请求); 我确定它会失败,因为它不可序列化。如果是的话应该是
一些可序列化的对象 class

(可序列化class 请求)

试试这个 var content = new StringContent(request, Encoding.UTF8, "application/json");

public 异步任务 RunTestAsync(字符串请求) { 尝试 { var content = new StringContent(JsonConvert.SerializeObject(请求),Encoding.UTF8,"application/json");

   var response=await this.client.PostAsync("http://localhost:8500/mat",
                          content);

    string str=await response.Content.ReadAsStringAsync();
    stringdata = JsonConvert.DeserializeObject<string>(str);
    return data;     
}
catch (Exception ex)
{
    Console.WriteLine("Threw in client" + ex.Message);
    throw;
}

}