从静态类返回IHttpActionResult的最佳方法

3

我正在尝试编写一个通用的方法来返回Web API 2中的内部服务器错误...

当我的Web API中的每个端点发生错误时,我会返回InternalServerError(new Exception("This is a custom message"))。我有几个站点使用相同的后端,但具有不同的URL,每个站点都有基于请求URI(company1.com、company2.com、company3.com)的自己的异常消息,因此我创建了一个通用方法:

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

但是,用同样的代码维护很多这样的方法有点困难(每个控制器都要一个),因此我认为创建一个使用相同方法的助手可以帮助减少我的代码量,使其更加干净和可维护,但我遇到了一个问题,当我这样做时return InternalServerError(new Exception("Custom message to company1, 2, 3"));

我知道返回InternalServerError是ApiController的一个特性,但拥有这个Helper将非常有帮助。

谢谢你的帮助。


你为什么不能将类型设置为InternalServerError而不是IHttpActionResult呢?在可能的情况下,我尽量避免将方法的类型设置为接口,而且似乎你总是返回一个InternalServerError。 - Daniel Casserly
InternalServerError 方法是什么?为什么要在这里创建异常?如何使用 getCustomMessage() 方法? - Sergey Berezovskiy
1个回答

1
你可以为ApiController类创建一个新的扩展方法:
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);
        }
    }
}
然后在控制器中:
return this.GetCustomMessage();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,