C# 从静态类返回IHttpActionResult的最佳方法
我正在尝试编写一个通用方法,用我的Web API 2返回一个内部服务器错误 当Web API中的每个端点发生错误时,我返回一个C# 从静态类返回IHttpActionResult的最佳方法,c#,asp.net,.net,asp.net-web-api2,C#,Asp.net,.net,Asp.net Web Api2,我正在尝试编写一个通用方法,用我的Web API 2返回一个内部服务器错误 当Web API中的每个端点发生错误时,我返回一个InternalServerError(新异常(“这是一条自定义消息”)。我有几个网站使用相同的后端和不同的URL,每个网站都有自己的基于请求URI的异常消息(company1.com、company2.com、company3.com),因此我创建了一个通用方法: private IHttpActionResult getCustomMessage() { if
InternalServerError(新异常(“这是一条自定义消息”)
。我有几个网站使用相同的后端和不同的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"));
}
}
但是用相同的代码维护很多这样的方法有点困难(一个由控制器,我有很多控制器),所以我认为用相同的方法创建一个帮助器可以帮助减少我的代码并使其更干净和可维护,但是我遇到了一个问题,当我这样做时返回InternalServerError(新异常(“给公司的自定义消息1、2、3”);
我知道返回InternalServerError是ApiController的一项功能,但如果有这个助手,那将非常有用
感谢您的帮助。您可以为ApicController类创建一个新的扩展方法:
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();
为什么不能使用InternalServerError类型而不是IHttpActionResult?我尽量避免将方法类型作为接口,似乎总是返回InternalServerError什么是
InternalServerError
方法?为什么在这里创建异常?如何使用getCustomMessage()
方法?