C# 如何在DelegatingHandler中手动返回json内容
这是我的代表团C# 如何在DelegatingHandler中手动返回json内容,c#,dotnet-httpclient,C#,Dotnet Httpclient,这是我的代表团 public class MyHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { MyCustomClass obj = GetMyCustomOb
public class MyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
MyCustomClass obj = GetMyCustomObject();
HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK);
response.Content = GetJsonContent(obj);
return Task.FromResult(response);
}
private HttpContent GetJsonContent(object obj)
{
throw new NotImplementedException();
}
}
公共类MyHandler:DelegatingHandler
{
受保护的覆盖任务SendAsync(HttpRequestMessage请求,CancellationToken CancellationToken)
{
MyCustomClass obj=GetMyCustomObject();
HttpResponseMessage response=request.CreateResponse(HttpStatusCode.OK);
response.Content=GetJsonContent(obj);
返回Task.FromResult(响应);
}
私有HttpContent GetJsonContent(对象obj)
{
抛出新的NotImplementedException();
}
}
如何将obj
作为json结果返回 您可能想试试
response.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
使用
新的StringContent(…)
和您喜欢的json序列化程序。@DanielA.White问题在于StringContent响应的内容类型是文本/普通;charset=utf-8
notjson
@DanielA.White谢谢!