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
not
json
@DanielA.White谢谢!