Uniform, consistent error responses from ASP.Net Web API 2

后端 未结 2 1688
醉话见心
醉话见心 2020-12-30 03:36

I\'m developing a Web API 2 application and I\'m currently trying to format error resposnes in a uniform way (so that the consumer will also know what data object/structure

2条回答
  •  北海茫月
    2020-12-30 04:12

    I have done in same way as @Dan H mentioned

     public class ApiGatewayHandler : DelegatingHandler
    {
        protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                var response = await base.SendAsync(request, cancellationToken);
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    var objectContent = response.Content as ObjectContent;
                    return await Task.FromResult(new ApiResult(HttpStatusCode.NotFound, VmsStatusCodes.RouteNotFound, "", objectContent == null ? null : objectContent.Value).Response());
                }
                return response;
            }
            catch (System.Exception ex)
            {
                return await Task.FromResult(new ApiResult(HttpStatusCode.BadRequest, VmsStatusCodes.UnHandledError, ex.Message, "").Response());
            }
    
        }
    }
    

    Added routing like below and now it hits the try catch for invalid url

      config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional });
            config.Routes.MapHttpRoute(name: "NotFound", routeTemplate: "api/{*paths}", defaults: new { controller = "ApiError", action = "NotFound" });
    

提交回复
热议问题