Web Api: recommended way to return json string

前端 未结 4 792
一个人的身影
一个人的身影 2020-12-10 15:57

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 HttpResponseMessag

4条回答
  •  醉话见心
    2020-12-10 16:37

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

    ...that can then be applied to ApiController derived classes. Greatly simplifying previous calls to

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

    or with desired HTTP status code

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

提交回复
热议问题