Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi's custom exception when "does not support http method"

I have a simple controller :

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

         }
   }

As you can see , only POST is currently available .

But when I invoke a GET in a browser (just for checking):

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

I get :

{"Message":"The requested resource does not support http method 'GET'."}

It is clear to me why it happens. But I want to return a custom exception when it happens.

Other answers here at SO doesn't show how I can treat this kind of situation (not that i've found of, anyway)

Question

How (and where) should I catch this kind of situation and return custom exception (HttpResponseMessage) ?

NB

I don't want to add a dummy GET method just for "catch and throw". tomorrow there can be a GET method. I just want to catch this Exception and return my OWN !

like image 772
Royi Namir Avatar asked Feb 02 '26 22:02

Royi Namir


1 Answers

You may need to inherit from ApiControllerActionSelector class which is what the Web API uses to select the required action.

then you can replace the default IHttpActionSelector by your new action selector like that. config.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector());

check this url for full example: http://www.strathweb.com/2013/01/magical-web-api-action-selector-http-verb-and-action-name-dispatching-in-a-single-controller/

like image 157
Omar.Alani Avatar answered Feb 04 '26 10:02

Omar.Alani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!