Return empty json on null in WebAPI

后端 未结 4 1004
野性不改
野性不改 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:36

    You can use a HttpMessageHandler to perform behaviour on all requests. The example below is one way to do it. Be warned though, I whipped this up very quickly and it probably has a bunch of edge case bugs, but it should give you the idea of how it can be done.

      public class NullJsonHandler : DelegatingHandler
        {
            protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
    
                var response = await base.SendAsync(request, cancellationToken);
                if (response.Content == null)
                {
                    response.Content = new StringContent("{}");
                } else if (response.Content is ObjectContent)
                {
                    var objectContent = (ObjectContent) response.Content;
                    if (objectContent.Value == null)
                    {
                        response.Content = new StringContent("{}");
                    }
    
                }
                return response;
            }
        }
    

    You can enable this handler by doing,

    config.MessageHandlers.Add(new NullJsonHandler());
    

提交回复
热议问题