我正在尝试向服务器发送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
!