Web Api:推荐的返回json字符串的方法 [英] Web Api: recommended way to return json string
问题描述
我有一些服务已经接收到必须返回给客户端的json字符串(不是对象).当前,我正在显式创建HttpResponseMessage
并将其Content
属性设置为服务接收的json字符串:
I've got a couple of services which already receive a json string (not an object) that must be returned to the client. Currently, I'm creating the HttpResponseMessage
explicitly and setting its Content
property to the json string which the service receives:
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonUtilizadores, Encoding.UTF8, "application/json");
return response;
现在,使用新的IHttpActionResult
有更好的方法吗?使用Content
或Ok
方法最终将json字符串括在引号中,这不是我想要的.
Now, is there a better way of doing this with the new IHttpActionResult
? Using the Content
or Ok
method ends up wrapping the json string with quotes, which is not what I want.
有任何反馈意见吗?
推荐答案
创建自定义实现.该框架可通过IHttpActionResult
进行扩展.
Create custom implementation. The framework is extensible via the IHttpActionResult
.
以下内容将创建自定义结果和扩展方法...
The following creates a custom result and extension method...
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
派生类.大大简化了以前对
...that can then be applied to ApiController
derived classes. Greatly simplifying previous calls to
return this.JsonString(jsonUtilizadores); //defaults to 200 OK
或具有所需的HTTP状态代码
or with desired HTTP status code
return this.JsonString(jsonUtilizadores, HttpStatusCode.BadRequest);
这篇关于Web Api:推荐的返回json字符串的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!