c# - 无法从 POST 请求反序列化 HttpContent
问题描述
我正在尝试向服务器发送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
并且它length
是null
!
解决方案
在您的示例中,客户端代码调用路由“/mat”,但中间件配置在“/mid”。如果你正在运行的代码有同样的错误,中间件不会被命中,你总是会从客户端得到一个空响应,看起来就像中间件收到了一样null
。确保您还使用了正确的端口号——我的 was :5000
,但它可能会因运行时配置而异。
您是否使用调试器和断点进行测试?如果没有,我强烈建议尝试。我能够很快找到该错误,因为我在服务器端代码中设置了一个断点,并观察到它没有被命中。如果调试器不是一个选项,请考虑通过抛出异常(而不是简单地返回)来“大声失败”,以使您是否真正达到您认为您正在达到的条件更加明显。
推荐阅读
- java - 如何使用 Java 下载 Mapbox PBF 文件?
- html - 如何让div占据全高
- r - 在 R 中使用 image():如何在 x 轴上左对齐刻度线?
- reactjs - 如何将会话详细信息传递给反应中的功能组件?
- excel - 从 IE 的下拉列表中选择一个选项并触发一个功能
- javascript - 当服务器端对 ag-grid 中的列进行排序时,它从第一页开始请求
- javascript - Array.push 不是 Promise 内部的函数
- docker - 使用 ansible 停止所有现有的 docker 容器
- r - 使用ggplot在分类X轴上连接来自不同组的点
- javascript - 如何使用 XMLHttpRequest 模拟文件上传?