c# - Web API 异常包装器

标签 c# asp.net-web-api exception httpresponse

我正在使用 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);
        }
    }
}

当抛出异常时,它会被捕获并准备好消息。通过重新抛出,我收到一条新的错误消息:

Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.

如何正确返回此异常,而 Visual Studio 不会提示?当我跳过错误时,浏览器会收到 501 错误结果。 方法 Request.CreateResponse() 在我的包装方法中不可用。

最佳答案

好吧,虽然这可能有效,但我建议您为此创建一个ExceptionFilterAttribute。这样,您就不必使用相同的臃肿代码来保护每个方法的异常。

例如:

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

您可以通过多种方式使用此过滤器:

<强>1。通过行动

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

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。通过 Controller :

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

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

<强>3。全局

要将过滤器全局应用到所有 Web API Controller ,请将过滤器的实例添加到 GlobalConfiguration.Configuration.Filters 集合中。此集合中的异常(exception)过滤器适用于任何 Web API Controller 操作。

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

如果您使用“ASP.NET MVC 4 Web 应用程序”项目模板来创建项目,请将 Web API 配置代码放入 WebApiConfig 类中,该类位于 App_Start 中 文件夹:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new FaultExceptionFilterAttribute());

        // Other configuration code...
    }
}

关于c# - Web API 异常包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244238/

相关文章:

javascript - Jquery Datepicker 日期格式在 Asp.net 中不起作用

c# - Dapper 多选 : Nested class primary key doesn't map unless using "AS"

azure - 为什么切换到 Azure Web 应用程序/API 到 Multi-Tenancy 不起作用?

java - 根据 double 数组对字符串数组进行排序

java - @Secured 抛出 AccessDeniedException 尽管角色是正确的

c# - System.Web.Routing.RouteCollection.GetRouteData 中的异常

c# - 使用 PerRequestLifetimeManager() 配置的 Unity 针对 WebApi 请求而非 MVC 请求创建多个 DbContext 实例

c# - WebAPI 通过传递参数未在 Controller 上找到任何操作

azure - Azure sql DB 中的最大池大小与并发登录数

.net - TryFoo是否应该抛出异常?