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!

  • 1
    Does this answer your question? [How do I redirect a user to a custom 404 page in ASP.NET MVC instead of throwing an exception?](https://stackoverflow.com/questions/19941/how-do-i-redirect-a-user-to-a-custom-404-page-in-asp-net-mvc-instead-of-throwing) – GSerg Mar 10 '21 at 10:40
  • 1
    Just changing the text in routedata to OrderFood should work i think. Asp will understand that GET route goes to the lower one and post to top one even if both have the same routedata – Ihusaan Ahmed Mar 10 '21 at 10:41
  • Hello @GSerg That answer don't resolve my issue –  Mar 10 '21 at 10:46
  • I had a route default is Home, i need a another specific route to resolve error! –  Mar 10 '21 at 10:48
  • Which framework are you using? .NET core or .NET framework? – Arib Yousuf Mar 11 '21 at 20:43
  • Hello, present i using .NET framework, web api v2 –  Mar 12 '21 at 03:11
  • 1
    @TrietPham Check my answer below. – Arib Yousuf Mar 12 '21 at 09:23

1 Answers1

0

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,230
  • 1
  • 8
  • 12