WebApi2 OData返回自定义错误对象

时间:2017-04-14 13:33:04

标签: c# error-handling asp.net-web-api2 odata

我已经搜索了这个密集型但却无法使用它。

我没有Web AP2 OData API,需要返回自定义错误类。

这就是我所拥有的:

public class Error
{
    public string Code { get; set; }
    public string Message { get; set; }
}

在Global.asax.cs

protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);            

        GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageInterceptor());
    }


 public class MessageInterceptor : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        return base.SendAsync(request, cancellationToken).ContinueWith(
                    task =>
                    {
                        var body = task.Result.Content.ReadAsStringAsync().Result;
                        var resultObj = JsonConvert.DeserializeObject(body.Replace("value", "Results"));                            
                        task.Result.Content = new ObjectContent(typeof(object), resultObj, new JsonMediaTypeFormatter());
                        return task.Result;
                    }, cancellationToken);
    }
}

在WebApiConfig中,cs

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

 config.Filters.Add(new  HandleApiExceptionAttribute());

}

}

public class HandleApiExceptionAttribute : ExceptionFilterAttribute, IExceptionFilter
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is Error)
        {
            var res = context.Exception.Message;

            //Define the Response Message
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(res),
                ReasonPhrase = res
            };

            //Create the Error Response
            context.Response = response;
        }
    }


 public class OrdersController : ODataControllerA controller
{
    private Context db = new Context();

    // GET: odata/Orders
    [Queryable]
    public IQueryable<Orders> GetOrders(ODataQueryOptions<Orders> opts)

{

<some code producing error>

Error theError = new Error()
        {
            Code = "1000",
            Message = "Geen filter gespecificeerd"
        };

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, theError);
        //return Request.CreateResponse(HttpStatusCode.BadRequest, theError);
        throw new HttpResponseException(response);

}

当我尝试这个时,它会在MessageInterceptor中崩溃。

这是因为使用API​​的第三方希望以特定格式使用它。

当代码运行正确时,它返回结果{}

出错时应该返回错误{code:,message:}

任何想法?

的Jeroen

1 个答案:

答案 0 :(得分:1)

这就是我提出的:

我将控制器更改为:

 [Queryable, BasicAuthentication]
    public IHttpActionResult GetOrders(ODataQueryOptions<Orders> opts)
    {
        else
        {     

            Error theError = new Error()
            {
                Code = "1000",
                Message = "Geen filter gespecificeerd"
            };

            return new ErrorResult(theError, Request);

        }

        return Ok(resultList);
    }

使用此课程:

public class ErrorResult : IHttpActionResult
{
    Error _error;
    HttpRequestMessage _request;

    public ErrorResult(Error error, HttpRequestMessage request)
    {
        _error = error;
        _request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {            

        List<Error> _errorList = new List<Error>();
        _errorList.Add(_error);

        error err = new error()
        {
            errors = _errorList
        };

        var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new ObjectContent<error>(err, new JsonMediaTypeFormatter()),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

public class Error 
{
    public string Code { get; set; }
    public string Message { get; set; }
}

public class error
{
    public List<Error> errors { get; set; }
}