Search code examples
c#asp.net-web-apiattributerouting

Is it possible to hardcode response in web api?


I need to call a web service every 5 minutes which tells if the system down. The problem is if the server is down, the system does not call the controller. We are using attribute routing. If the server is down I need to create a hardcoded response but since it does not go to the controller, I cannot hardcode the response.

How do I call the controller even if there is exception.


Solution

  • A. If the system is down it cannot generate a response. But that's a good thing, otherwise you would not be able to detect if it's down or not.

    B. If there's an exception the client will still get a response (500 for example) which tells it that the server is up (but with problems).

    C. On the controller level I think this is the best you can do:

    [Route("/alive")]
    [AllowAnonymous]
    [HttpGet]
    public string Alive()
    {
       return "I'm alive and loving it!";
    }
    

    D. For setting up custom error response for errors please see Global Error Handling in ASP.NET Web API 2 or Exception Handling in ASP.NET Web API's Exception Filters:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());
    
            // Other configuration code...
        }
    }