如何捕捉形式在ASP.NET MVC4的Web API授权错误 [英] How to catch forms authorization error in Web API in ASP.NET MVC4

查看:333
本文介绍了如何捕捉形式在ASP.NET MVC4的Web API授权错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET /单声道MVC4的Web API应用.1

ASP.NET / Mono MVC4 Web API v.1 application.

API控制器使用窗体authorication,并与标准的装饰[授权]
属性。
如果授权失败,标准API的错误消息

API controllers are using Forms authorication and are decorated with standard [Authorize] attribute. If authorization fails, standard api error message

<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>

发生。
如何itercept此错误sriting日志文件。
错误信息返回给调用者shoudl保持不变。
如何添加额外的code这个可以写了这个错误消息,整个HTTP
请求头和身体日志文件?

occurs. How to itercept this error for sriting to log file . Error message returned to caller shoudl remain the same. how to add additional code to this which can wrote this error message with whole http request headers and body to log file ?

我添加code从问题

<一个href=\"http://stackoverflow.com/questions/15167927/how-do-i-log-all-exceptions-globally-for-a-c-sharp-mvc4-webapi-app\">How我在全球记录所有的例外是C#MVC4的WebAPI应用?

<一个href=\"http://stackoverflow.com/questions/20212725/how-to-catch-undefined-api-method-calls-in-asp-net-mvc4-web-api\">How赶上未定义的API方法调用ASP.NET MVC4的Web API

但没有逮住athorization错误。

but athorization error is not catched.

如何捕捉所有的错误?

更新

code需要在Windows中运行2003服务器。
我试过code从答案,但得到的编译错误

code needs to run in Windows 2003 server. I tried code from answer but got compile errors

Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?

如何int类型W2003服务器上运行?

How to run int in W2003 server ?

推荐答案

你可以做到这一点的方法之一是写一个DelegatingHandler拦截响应之前它被发送回客户端,然后再登录那些返回请求的信息错误。

One way you could achieve this is to write a DelegatingHandler to intercept the response before it gets sent back to the client, and then log information on those requests that return errors.

public class RepsonseInterceptor : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        LogResponse(request, response);

        return response;
    }

    public void LogResponse(HttpRequestMessage request, HttpResponseMessage response)
    {
        HttpStatusCode status = response.StatusCode;
        //Catch the status codes you want to Log
        if (status == HttpStatusCode.NotFound || status == HttpStatusCode.Unauthorized || status == HttpStatusCode.InternalServerError)
        {
            //Do Logging Stuff here
            //with the Request and Response
        }
    }
}

那么这在Global.asax.cs中添加到的Application_Start:

Then add this to the Application_Start in the Global.asax.cs:

GlobalConfiguration.Configuration.MessageHandlers.Add(new ResponseInterceptor());

编辑:

如果您不希望执行的处理程序,所有的路由可以将其添加为每路由消息处理程序你想要的,而不是全局像这样的路线:

If you don't want to execute the handler for all routes you can add it as a Per-Route Message Handler to those routes you want instead of globally like so:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: null,
    handler: new ResponseInterceptor()
    );

如果您使用的是.NET Framework 4.0中您需要更改的处理程序的SendAsync方法如下:

If you are using .NET Framework 4.0 you need to change the SendAsync method of the handler as follows:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    return base.SendAsync(request, cancellationToken)
      .ContinueWith(task =>
      {
          var response = task.Result;
          LogResponse(request, response);
          return response;
       });
}

我认为这将是合理的,只是用这个的MessageHandler如果你能获得所有的,你需要从Request和Response对象记录的信息,虽然我还没有完全测试了这一点。

I think it would be reasonable to just use this MessageHandler if you can obtain all of the information that you need to log from the Request and Response objects, although I've not fully tested this out.

这篇关于如何捕捉形式在ASP.NET MVC4的Web API授权错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆