3

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 !

3
  • Do you want to throw an exception is your production code, or just assert for routes in tests? Commented Oct 23, 2014 at 9:32
  • @SrikanthVenugopalan I want to catch this situation and return http exception. (error response). yes in production. Also - routing stage is too early to know if an action exists or not. Commented Oct 23, 2014 at 9:34
  • Hmm, for a moment I was tempted to point you to the WebApiContrib.Testing that I use for asserting routes. Commented Oct 23, 2014 at 9:39

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Omar , Isit possible to go to chat regarding this question ?
Sure, how can I help?
0

You can build custom Exception filters in ASP.Net WebAPI. An exception filter is a class that implements the IExceptionFilter interface. To create a custom exception filter you can either implement the IExceptionFilter interface yourself or create a class that inherits from the inbuilt ExceptionFilterAttribute class. In the later approach all you need to do is override the OnException() method and plug-in some custom implementation.

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

you would likely want to test for conditions and generate the exact exception, but this is a bare example.

To use the exception class, you can either register it in the Global.asax, or as an attribute on a specific class or method.

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

or

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

3 Comments

Also , OnException is not hit when debug
(just divided 1/0 and OnException does enter , so I guess 405 is not an exception ??)
maybe this article might shed some light on the subject? ruhul.wordpress.com/2014/09/05/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.