c# – Web Api:推荐返回json字符串的方法

前端之家收集整理的这篇文章主要介绍了c# – Web Api:推荐返回json字符串的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个服务已经收到一个必须返回给客户端的json字符串(不是对象).目前,我正在显式创建HttpResponseMessage并将其Content属性设置为服务接收的json字符串:
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonUtilizadores,Encoding.UTF8,"application/json");
return response;

现在,使用新的IHttpActionResult有更好的方法吗?使用Content或Ok方法最终用引号包装json字符串,这不是我想要的.

任何反馈?

解决方法

创建自定义实现.该框架可通过IHttpActionResult进行扩展.

以下创建自定义结果和扩展方法……

public static class JsonStringResultExtension {
   public static CustomJsonStringResult JsonString(this ApiController controller,string jsonContent,HttpStatusCode statusCode = HttpStatusCode.OK) {
        var result = new CustomJsonStringResult(controller.Request,statusCode,jsonContent);
        return result;
    }

    public class CustomJsonStringResult : IHttpActionResult {
        private string json;
        private HttpStatusCode statusCode;
        private HttpRequestMessage request;

        public CustomJsonStringResult(HttpRequestMessage httpRequestMessage,HttpStatusCode statusCode = HttpStatusCode.OK,string json = "") {
            this.request = httpRequestMessage;
            this.json = json;
            this.statusCode = statusCode;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
            return Task.FromResult(Execute());
        }

        private HttpResponseMessage Execute() {
            var response = request.CreateResponse(statusCode);
            response.Content = new StringContent(json,"application/json");
            return response;
        }
    }
}

…然后可以应用于ApiController派生类.大大简化以前的通话

return this.JsonString(jsonUtilizadores); //defaults to 200 OK

或者使用所需的HTTP状态代码

return this.JsonString(jsonUtilizadores,HttpStatusCode.BadRequest);
原文链接:https://www.f2er.com/csharp/97736.html

猜你在找的C#相关文章