Return empty json on null in WebAPI

后端 未结 4 1054
野性不改
野性不改 2021-02-04 02:50

Is it possible to return { } instead of null when webApi returns a null object? This, to prevent my user from getting errors while parsing the response. And to make the respon

4条回答
  •  甜味超标
    2021-02-04 03:29

    Thanks to Darrel Miller, I for now use this solution.


    WebApi messes with StringContent "{}" again in some environment, so serialize through HttpContent.

    /// 
    /// Sends HTTP content as JSON
    /// 
    /// Thanks to Darrel Miller
    /// 
    public class JsonContent : HttpContent
    {
        private readonly JToken jToken;
    
        public JsonContent(String json) { jToken = JObject.Parse(json); }
    
        public JsonContent(JToken value)
        {
            jToken = value;
            Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            var jw = new JsonTextWriter(new StreamWriter(stream))
            {
                Formatting = Formatting.Indented
            };
            jToken.WriteTo(jw);
            jw.Flush();
            return Task.FromResult(null);
        }
    
        protected override bool TryComputeLength(out long length)
        {
            length = -1;
            return false;
        }
    }
    
    
    

    Derived from OkResult to take advantage Ok() in ApiController

    public class OkJsonPatchResult : OkResult
    {
        readonly MediaTypeWithQualityHeaderValue acceptJson = new MediaTypeWithQualityHeaderValue("application/json");
    
        public OkJsonPatchResult(HttpRequestMessage request) : base(request) { }
        public OkJsonPatchResult(ApiController controller) : base(controller) { }
    
        public override Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var accept = Request.Headers.Accept;
            var jsonFormat = accept.Any(h => h.Equals(acceptJson));
    
            if (jsonFormat)
            {
                return Task.FromResult(ExecuteResult());
            }
            else
            {
                return base.ExecuteAsync(cancellationToken);
            }
        }
    
        public HttpResponseMessage ExecuteResult()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new JsonContent("{}"),
                RequestMessage = Request
            };
        }
    }
    

    Override Ok() in ApiController

    public class BaseApiController : ApiController
    {
        protected override OkResult Ok()
        {
            return new OkJsonPatchResult(this);
        }
    }
    

    提交回复
    热议问题