0

我正在尝试向服务器发送POST请求。请求进入Middleware'Invoke方法。

但是Content,无论对象的类型如何,它始终为空。

发件人

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定义,只是一个middleware响应route. (请求进入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在另一边得到一个。

PS

我也尝试过使用不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

4

3 回答 3

1

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

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

于 2019-02-07T04:14:30.563 回答
1

不确定您的代码到底有什么问题,但这有效:

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}

于 2019-02-07T04:51:41.703 回答
0

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

调用 RunTestAsync(request); 只运行这个 JsonConvert.SerializeObject(request); 我确定它失败了,因为它不可序列化。如果是,它应该是可
序列化类的某个对象

(可序列化类请求)

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

公共异步任务 RunTestAsync(字符串请求){ 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;
}

}

于 2019-02-09T00:42:52.090 回答