首页 文章

Web API异常包装器

提问于
浏览
2

我正在使用WebAPI来调用某些第三方方法:

public class SessionsController : ApiController
{
    public DataTable Get(int id)
    {
        return Services.TryCall(es => es.GetSessionList(id).Tables[0]);
    }
}

我正在打包这项服务的所有电话:

internal static class Services
{
    internal static IExternalService ExternalService { get; set; }

    internal static T TryCall<T>(Func<IExternalService,T> theFunction)
    {
        try
        {
            return theFunction(ExternalService);
        }
        catch (FaultException<MyFaultDetail> e)
        {
            var message = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            message.Content = new StringContent(e.Detail.Message);
            throw new HttpResponseException(message);
        }
    }
}

抛出异常时,会捕获它并准备好消息 . 通过重新抛出我得到一个新的错误消息:

处理HTTP请求导致异常 . 有关详细信息,请参阅此异常的“响应”属性返回的HTTP响应 .

如果没有Visual Studio抱怨,我怎样才能正确返回此异常?当我跳过错误时,浏览器会收到501错误结果 . 方法 Request.CreateResponse() 在我的包装器方法中不可用 .

1 回答

  • 3

    好吧,虽然这可行,但我建议您为此创建一个 ExceptionFilterAttribute . 这样,您就不必使用相同的膨胀代码来保护每个异常方法 .

    例如:

    public class FaultExceptionFilterAttribute : ExceptionFilterAttribute 
        {
            public override void OnException(HttpActionExecutedContext context)
            {
                if (context.Exception is FaultException)
                {
                    context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
                }
            }
        }
    

    有几种方法可以使用此过滤器:

    1. By Action

    要将过滤器应用于特定操作,请将过滤器作为属性添加到操作中:

    public class SampleController : ApiController
    {
        [FaultExceptionFilter]
        public Contact SampleMethod(int id)
        {
           //Your call to a method throwing FaultException
            throw new FaultException<MyFaultDetail>("This method is not implemented");
        }
    }
    

    2. By Controller:

    要将过滤器应用于控制器上的所有操作,请将过滤器作为属性添加到控制器类:

    [FaultExceptionFilter]
    public class SampleController : ApiController
    {
        // ...
    }
    

    3. Globally

    要将筛选器全局应用于所有Web API控制器,请将筛选器的实例添加到 GlobalConfiguration.Configuration.Filters 集合中 . 此集合中的Exeption过滤器适用于任何Web API控制器操作 .

    GlobalConfiguration.Configuration.Filters.Add(new FaultExceptionFilterAttribute());
    

    如果使用"ASP.NET MVC 4 Web Application"项目模板来创建项目,请将Web API配置代码放在 WebApiConfig 类中,该类位于 App_Start 文件夹中:

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

相关问题