【问题标题】:WebApi's custom exception when "does not support http method"“不支持http方法”时WebApi的自定义异常
【发布时间】:2014-10-24 08:54:38
【问题描述】:

我有一个简单的控制器:

   public class UsersController : ApiController
    {
        [HttpPost]
        [AllowAnonymous]
         public HttpResponseMessage Login([FromBody] UserLogin userLogin)
         {
             var userId = UserCleaner.Login(userLogin.MasterEntity, userLogin.UserName, userLogin.Password, userLogin.Ua);
             if (userId == null) return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User not authorized");
             return Request.CreateResponse(HttpStatusCode.OK, Functions.RequestSet(userId)); 

         }
   }

如您所见,目前只有 POST 可用。

但是当我在浏览器中调用 GET 时(仅用于检查):

http://royipc.com:88/api/users

我明白了:

{"Message":"请求的资源不支持http方式 '得到'。"}

我很清楚为什么会这样。但我想在它发生时返回一个自定义异常。

SO 的其他答案并没有显示我如何处理这种情况(反正我没有找到)

问题

我应该如何(以及在​​哪里)捕捉到这种情况并返回自定义异常(HttpResponseMessage)?

注意

我不想只为“catch and throw”添加一个虚拟的 GET 方法。 明天可以有一个 GET 方法。我只想抓住这个异常并返回我的 OWN!

【问题讨论】:

  • 你想抛出一个异常是你的生产代码,还是仅仅断言测试中的路由?
  • @SrikanthVenugopalan 我想捕捉这种情况并返回 http 异常。 (错误响应)。是的,在生产中。 另外 - 路由阶段还为时过早,无法知道某个操作是否存在。
  • 嗯,有那么一刻我很想给你指出我用来声明路由的WebApiContrib.Testing

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


【解决方案1】:

您可能需要从 ApiControllerActionSelector 类继承,这是 Web API 用来选择所需操作的类。

然后您可以像这样用新的操作选择器替换默认的 IHttpActionSelector。 config.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector());

查看此网址以获取完整示例:http://www.strathweb.com/2013/01/magical-web-api-action-selector-http-verb-and-action-name-dispatching-in-a-single-controller/

【讨论】:

  • 奥马尔,可以就这个问题去聊天吗?
  • 好的,请问有什么可以帮忙的?
【解决方案2】:

您可以在 ASP.Net WebAPI 中构建自定义异常过滤器。异常过滤器是一个实现IExceptionFilter 接口的类。要创建自定义异常过滤器,您可以自己实现IExceptionFilter 接口,也可以创建一个继承自内置ExceptionFilterAttribute 类的类。在后面的方法中,您需要做的就是覆盖OnException() 方法并插入一些自定义实现。

public class MyExceptionFilter:ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent("An unhandled exception was thrown by the Web API controller."),
            ReasonPhrase = "An unhandled exception was thrown by the Web API controller."
        };
        context.Response = msg;
    }
}

您可能希望测试条件并生成确切的异常,但这只是一个简单的示例。

要使用异常类,您可以在 Global.asax 中注册它,或者作为特定类或方法的属性。

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configuration.Filters.Add(new WebAPIExceptionsDemo.MyExceptionFilter());
        AreaRegistration.RegisterAllAreas();
        ...
    }
}

[MyExceptionFilter]
public class UsersController : ApiController
{
...
}

【讨论】:

  • 另外,OnException 在调试时不会被命中
  • (只是除以 1/0 并且 OnException 确实进入了,所以我猜 405 也不例外??)
  • 也许这篇文章可能会对这个主题有所启发? ruhul.wordpress.com/2014/09/05/…
猜你喜欢
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2020-03-28
  • 2017-10-17
  • 1970-01-01
  • 2022-01-15
  • 2016-11-18
  • 1970-01-01
相关资源
最近更新 更多