Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在异常筛选器中获取WebApi异常响应_C#_.net_Asp.net Web Api - Fatal编程技术网

C# 在异常筛选器中获取WebApi异常响应

C# 在异常筛选器中获取WebApi异常响应,c#,.net,asp.net-web-api,C#,.net,Asp.net Web Api,我们安装了一个异常过滤器 public class APIErrorHandlerAttribute : ExceptionFilterAttribute, IExceptionFilter { // Sets up log4net logger private static readonly log4net.ILog log = log4net.LogManager.GetLogger (System.Reflection.MethodBase.GetCurr

我们安装了一个异常过滤器

public class APIErrorHandlerAttribute : ExceptionFilterAttribute, IExceptionFilter
{
     // Sets up log4net logger
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger
        (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is BusinessException)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Exception"
            });

        }

        //Log Critical errors
        log.Info("/****************** API Begin Error ******************/");
        log.Info("Exception:" + context.Exception + "  Case:" + CaseHelper.GetCurrentCaseID() + "  UserID:" + UserHelper.GetCurrentUserID());
        log.Info("/****************** API End Error ******************/");

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(string.Format("Message: {0}\nStack Trace: {1}", context.Exception.Message, context.Exception.StackTrace)),
            ReasonPhrase = "Critical Exception",
        });
    }
}
适用于所有WebApi路由

    //*** Log API Error Globally using Log4net
    public static void RegisterFilters(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute("DefaultApiError", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
        config.Filters.Add(new LRAPIErrorHandlerAttribute());
    }
我们还有一个附加到某些控制器的授权属性。它看起来像这样:

public class LegalRadiusAPIAuthorizationAttribute : ActionFilterAttribute, IActionFilter, IFilter
{
    public string Permissions { get; set; }
    public string Roles { get; set; }
    public string Users { get; set; }

    public override void OnActionExecuted(HttpActionExecutedContext filterContext)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            throw new HttpResponseException(HttpStatusCode.NonAuthoritativeInformation); //203
        }
     }
}
因此,如果未经身份验证的用户点击了要求其登录的路由,我们将抛出。如果我在此筛选器内进行调试并打开“异常”对话框,我可以在异常对象上看到以下属性:

如果我查看
响应
属性,就会看到抛出异常的所有相关细节

问题是当此异常由
apErrorHandlerAttribute
处理时。当异常到达处理程序时,我似乎无法在
上下文中找到异常的
响应
属性

尽管如此,在处理程序中,我从捕获的异常中得到以下错误消息:

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

这意味着上下文中的异常应该具有该属性

我觉得我遇到了范围问题,并且过滤器中抛出的原始异常对象不在异常处理程序的
上下文
参数中。

试试这个
var exceptionData=新的exceptionData
{
Name=“异常名称”,
Message=“异常消息”
};

Content=newobjectcontent(exceptionData,JsonFormatter),

您只需从
上下文中访问
[System.Web.Http.HttpResponseException]
。为此,根据图片,您需要在
[System.Web.Http.HttpResponseException]
右键单击
,并在其上添加一个
观察者。这将为您提供适当的
转换
,以便从
上下文
中检索信息


如果您单击
[System.Web.Http.HttpResponseException]
?@Hackerman上的
plus
图标,就可以了!现在,如何从
上下文.Exception
访问
[System.Web.Http.HttpResponseException]
?只需右键单击它并添加另一个手表。这将为您提供适当的强制转换,以便从上下文中检索信息:)这就是@Hackerman!把它写下来作为一个答案,这样我就可以把它标记为已被接受:d考虑完成……明天第一个小时:)