0

Controller

[Route("OrderFood")]
[HttpPost]
public IHttpActionResult OrderFood(Food foodinfo)
{
    //do something
    ...
}

[Route("ResolverError")]
public void ResolverError()
{
    //Return error in a frienly and logging detail about the caller in App Insights
    ...
}

App_Start/RouteConfig

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "Api/{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Hello, context is as follows: My system have some calls to method OrderFood by Postman, cause mistake so they call it with method GET. Of course, the call failed and response code 405.

So, my idea is if user request to OrderFood with method GET, i will detect it and redirect to route ResolverError. At here, i can manage exception and logging detail about the caller.

How about your idea? Thank you!

Triet Pham
  • 99
  • 2
  • 10

1 Answers1

1

Use Global.asax which is used for higher-level application events such as Application_Start, Session_Start, etc. In that file, we have an event called Application_PostRequestHandlerExecute which is fired when the framework has finished executing an event handler. You can use this event for your use case. Try the following code:

 protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
    {
        var response = HttpContext.Current.Response;
        if (response.StatusCode == 405)
        {
            Response.RedirectToRoute("Controller/ResolverError");
        }
    }

Getting Response from the HTTP context, checking the status code, and then redirecting the request to the specific controller.

Arib Yousuf
  • 1,171
  • 1
  • 7
  • 12