Best way to return IHttpActionResult from static class

I am trying to code a generic method to return an internal server error using my web API 2 ...

When there is an error on each endpoint of my web API, I return InternalServerError(new Exception("This is a custom message"))

. I have multiple sites using the same backend with different urls, each site has its own exception message based on the request URI (company1.com, company2.com, company3.com), so I created a generic method:

private IHttpActionResult getCustomMessage() {
    if(Request.RequestUri.Host.Contains("company1")) {
        return InternalServerError(new Exception("Custom message for company1"));
    }
    if(Request.RequestUri.Host.Contains("company2")) {
        return InternalServerError(new Exception("Custom message for company2"));
    }
    if(Request.RequestUri.Host.Contains("company3")) {
        return InternalServerError(new Exception("Custom message for company3"));
    }
}

      

But it is a little tricky to maintain many of these methods with the same code (one of the controllers and I have many controllers), so I think that creating a helper using the same method might help reduce my code and make it cleaner and more maintainable, but i have a problem when i do this return InternalServerError(new Exception("Custom message to company1, 2, 3"));

I know that the return of InternalServerError is a function of the ApiController, but it would be very helpful to have this helper.

Thank you for your help.

+3


source to share


1 answer


You can create a new extension method for the ApiController class:

public static class MyApiControllerExtensions
{
    public IHttpActionResult GetCustomMessage(this ApiController ctrl)
    {
        // this won't work because the method is protected
        // return ctrl.InternalServerError();

        // so the workaround is return whatever the InternalServerError returns
        if (Request.RequestUri.Host.Contains("company1")) 
        {
             return new System.Web.Http.Results.ExceptionResult(new Exception("Custom message for company1"), ctrl);
        }
        if (Request.RequestUri.Host.Contains("company2"))
        {
             return new System.Web.Http.Results.ExceptionResult(new Exception("Custom message for company2"), ctrl);
        }
        if (Request.RequestUri.Host.Contains("company3")) 
        {
             return new System.Web.Http.Results.ExceptionResult(new Exception("Custom message for company3"), ctrl);
        }
    }
}

      



Then in the controller:

return this.GetCustomMessage();

      

0


source







All Articles