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, Encoding.UTF8, "application/json");
            return response;
        }
    }
}

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

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

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

return this.JsonString(jsonUtilizadores, HttpStatusCode.BadRequest);

转载注明原文:c# – Web Api:推荐返回json字符串的方法 - 代码日志