在ASP.NET网页API 2异常处理 [英] Exception Handling in ASP.NET Web Api 2

查看:147
本文介绍了在ASP.NET网页API 2异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我需要处理Web API 2的异常和正确的状态code(401未经授权,404 ContentNotFound等),以及一些额外的信息作为内容返回一个丰富的对象。此外,我所需要的内容,看起来像一个序列化例外对象(有的消息 exceptionMessage 堆栈跟踪 ...属性)。

I need to handle web api 2 exceptions and return a rich object with the correct status code (401 for Unauthorized, 404 for ContentNotFound, etc) and some extra information as the content. Moreover, I need the content to look like a serialized Exception object (have the message, exceptionMessage, stackTrace, ... properties).

建议的解决方法:


  1. 创建自定义的异常类,并编写自定义异常过滤器适用于任何控制器的行动。这个自定义异常处理过滤器根据它的类型(即我已经定义的自定义异常之一)抛出的异常,并通过这样的事情(过滤器的code)做出相应的响应:

  1. Create custom exception classes and writing a custom exception filter to apply to any controller's action. this custom exception filters handles the exception thrown according to it's type (one of the custom exceptions that I've already defined) and responds accordingly via something like this (filter's code):

context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                                    new Exception("my exception")));


  • 包裹已经编写的Web API 2 *的ActionResult 类( System.Web.Http.Results.UnauthorizedResult未经授权() System.Web.Http.Results.OkResult好()等),并增加了一些自定义的数据和使用它们,使它们的结果获得通过客户每次他们是所谓的时间(这个问题是在这种情况下,我的控制器操作的返回类型应该是 IHttpActionResult 这是不一样容易测试和可读性强类型的动作)

  • wrapping the already written web api 2 *ActionResult classes ( System.Web.Http.Results.UnauthorizedResult Unauthorized(), System.Web.Http.Results.OkResult Ok(), etc ) and adding some custom data to them and use them so that their result get passed to client every time they're called (the problem is in this case my controller's action's return type should be IHttpActionResult which is not as easily testable and readable as a strongly typed action).

    有什么解决办法?或者有没有其他的方式做什么,我想在这里实现吗?

    What solution should I choose? Or is there any other way to do what I'm trying to achieve here?

    推荐答案

    或者你可以使用内置的,出的现成的解决方案:的异常过滤器

    Or you could use the built-in, out-of-the-box solution: exception filters.

    此外,您可能会感兴趣的<一个href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling\">exception处理来自网络API 2.X 开始。

    Furthermore, you may be interested on exception handling starting from Web API 2.x.

    这篇关于在ASP.NET网页API 2异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆