阻止拦截ASP.NET Web API响应的FormsAuthenticationModule

在ASP.NET中,FormsAuthenticationModule拦截任何HTTP 401,并返回HTTP 302重定向登录页面.这对AJAX来说很痛苦,因为你要求json并以html获取登录页面,但状态代码是HTTP 200.

在ASP.NET Web API中避免这种拦截方法是什么?

在ASP.NET MVC4中,通过明确结束连接来防止此拦截非常容易:

public class MyMvcAuthFilter:AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && !filterContext.IsChildAction)
        {
            filterContext.Result = new HttpStatusCodeResult(401);
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.HttpContext.Response.SuppressContent = true;
            filterContext.HttpContext.Response.End();
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

但是在ASP.NET Web API中我无法显式地结束连接,因此即使我使用此代码,FormsAuthenticationModule也会拦截响应并将重定向发送到登录页面

public class MyWebApiAuth: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if(actionContext.Request.Headers.Any(h=>h.Key.Equals("X-Requested-With",StringComparison.OrdinalIgnoreCase)))
        {
            var xhr = actionContext.Request.Headers.Single(h => h.Key.Equals("X-Requested-With",StringComparison.OrdinalIgnoreCase)).Value.First();

            if (xhr.Equals("XMLHttpRequest",StringComparison.OrdinalIgnoreCase))
            {
                // this does not work either
                //throw new HttpResponseException(HttpStatusCode.Unauthorized);

                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                return;
            }
        }

        base.HandleUnauthorizedRequest(actionContext);
    }
}

在ASP.NET Web API中避免此行为的方法是什么?我一直在看,我找不到办法.

问候.

PS:我不敢相信这是2012年,这个问题仍然存在.

解决方法

MVC 4 RC的发行说明意味着自Beta以来已经解决了这个问题 – 您使用的是什么?

http://www.asp.net/whitepapers/mvc4-release-notes
ASP.NET Web API处理的未经授权的请求返回401 Unauthroized:ASP.NET Web API处理的未经授权的请求现在返回标准的401 Unauthorized响应,而不是将用户代理重定向登录表单,以便Ajax客户端可以处理响应.

查看MVC的源代码,似乎通过SuppressFormsAuthRedirectModule.cs添加一个功能

http://aspnetwebstack.codeplex.com/SourceControl/network/forks/BradWilson/AspNetWebStack/changeset/changes/ae1164a2e339#src%2fSystem.Web.Http.WebHost%2fHttpControllerHandler.cs.

internal static bool GetEnabled(NameValueCollection appSettings)
    {
            // anything but "false" will return true,which is the default behavior

所以它看起来这是认启用的,RC应该修复你的问题,没有任何英雄……作为一个侧面点看起来你可以使用AppSettings http://d.hatena.ne.jp/shiba-yan/20120430/1335787815禁用这个新模块:

<appSettings> 
    <Add Key = "webapi:EnableSuppressRedirect"  value = "false" /> 
</appSettings>

编辑(示例和说明)

我现在已经在GitHub上为这种方法创建了一个示例.新的重定向抑制要求您使用两个正确的“授权”属性;控制器中的MVC Web [System.Web.Mvc.Authorize]和Web API [System.Web.Http.Authorize]和全局过滤器Link中的/或OR.

然而,该示例确实提出了该方法的限制.似乎web.config中的“授权”节点将始终优先于MVC路由,例如像这样的配置将覆盖您的规则并仍然重定向登录

<system.web>
    <authentication mode="Forms">
    </authentication>
    <authorization>
        <deny users="?"/> //will deny anonymous users to all routes including WebApi
    </authorization>
</system.web>

遗憾的是,使用Location元素打开一些url路由似乎不起作用,WebApi调用将继续被拦截重定向登录.

解决方

对于MVC应用程序,我只是建议从Web.Config删除配置,并在代码中坚持使用全局过滤器和属性.

如果你必须使用Web.Config for MVC中的授权节点或者有一个混合ASP.NET和WebApi应用程序,那么@PilotBob – 在下面的评论中 – 发现子文件夹和多个Web.Config可以用来制作你的蛋糕和吃了它.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you
以下内容来源于: http://blog.csdn.net/cuike519/archive/2005/09/27/490316.aspx 问:为什么Session在有些机器上偶尔会丢失? 答:可能和
以下文章提到可以用“http://localhost/MyWebApp/WebAdmin.axd”管理站点: ---------------------------------------------
Visual Studio 2005 IDE相关的11个提高开发效率的技巧 英文原创来源于: http://www.chinhdo.com/chinh/blog/20070920/top-11-vis
C#日期格式化 from: http://51xingfu.blog.51cto.com/219185/46222 日期转化一 为了达到不同的显示效果有时,我们需要对时间进行转化,默认格式为:2007
from: http://www.nikhilk.net/UpdateControls.aspx Two controls that go along with the UpdatePanel and
Open the report in the Designer. In the ToolBox, select/expand the &quot;Report Items&quot; section.
from: http://drupal.org/node/75844 Do this: find which TinyMCE theme you are using. For the sake of
asp.net中给用户控件添加自定义事件 用户控件中定义好代理和事件: public delegate void ItemSavedDelegate(object sender, EventArgs
在Windows版本的Safari中浏览以下的页面。 http://www.asp.net/AJAX/Control-Toolkit/Live/Calendar/Calendar.aspx Calen
http://aspnet.4guysfromrolla.com/articles/021506-1.aspx By Scott Mitchell Introduction When creating