修改.NET ApiController“BadResult()”以打印自定义JSON

时间:2016-08-08 21:15:44

标签: c# asp.net .net json json-api

我正在使用.NET模式,其中我的控制器操作具有签名

public async Task<IHttpActionResult> GetTimeSeries(string deviceId, string tag) { ... }

并且在控制器内部我想发送一个遵守JSON API Spec

的自定义错误消息

我的目标是在遇到错误时使用

return BadRequest(someJSONErrorObject); 

return NotFound(someJSONErrorObject); 

而不是抛出异常。

目前如果我这样做

return BadRequest(JsonConvert.SerializeObject(someJSONErrorObject));

我回来的JSON看起来像

{
"Message": "{\"data\":null,\"errors\":[{\"detail\":\"The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.\"}],\"meta\":null}"
}

2 个答案:

答案 0 :(得分:2)

创建自定义IHttpActionResult

public class CustomResponseResult<T> : IHttpActionResult {

    public CustomResponseResult(HttpStatusCode statusCode, T content, HttpRequestMessage request) {
        Content = content;
        Request = request;
        StatusCode = statusCode;
    }

    public T Content { get; private set; }
    public HttpRequestMessage Request { get; private set; }
    public HttpStatusCode StatusCode { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute() {
        var response = Request.CreateResponse(StatusCode, Content);
        response.RequestMessage = Request;
        response.ReasonPhrase = StatusCode.ToString();
        return response;
    }
}

然后为了保持可用性创建扩展方法

public static class ApiControllerExtensions {
    public static IHttpActionResult BadRequest<T>(this ApiController controller, T content) {
        return controller.CustomResponse(HttpStatusCode.BadRequest, content);
    }

    public static IHttpActionResult NotFound<T>(this ApiController controller, T content) {
        return controller.CustomResponse(HttpStatusCode.NotFound, content);
    }

    public static IHttpActionResult CustomResponse<T>(this ApiController controller, HttpStatusCode statusCode, T content) {
        var request = controller.Request;
        var result = new CustomResponseResult<T>(statusCode, content, request);
        return result;
    }
}

允许所需的电话

return this.BadRequest(someJSONErrorObject);

return this.NotFound(someJSONErrorObject);

答案 1 :(得分:0)

创建自定义错误类,您可以在其中设置http状态和错误消息。创建一个自定义异常类来抛出您的客户错误消息。创建一个全局异常过滤器,它将以json格式向您发送自定义异常。