如何在DelegatingHandler中手动返回json内容

问题描述 投票:0回答:1

这是我的委托处理人

    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();
        }

    }

如何返回obj作为json结果;

c# dotnet-httpclient
1个回答
0
投票

您可能想尝试

response.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
                                    Encoding.UTF8, 
                                    "application/json");//CONTENT-TYPE header
© www.soinside.com 2019 - 2024. All rights reserved.