WebApi';s自定义异常,当“;不支持http方法”;

本文关键字:不支持 http 方法 自定义异常 WebApi | 更新日期: 2023-09-27 18:27:28

我有一个简单的控制器:

   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)?

NB

我不想仅仅为"catch-and-throw"添加一个伪GET方法明天可能会有一个GET方法。我只想抓住这个异常并返回我自己的!

WebApi';s自定义异常,当“;不支持http方法”;

您可能需要从ApiContrlerActionSelector类继承,Web API使用该类来选择所需的操作。

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

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

您可以在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
{
...
}