【问题标题】:Prevent FormsAuthentication from overriding the response status in WCF REST防止 FormsAuthentication 覆盖 WCF REST 中的响应状态
【发布时间】:2011-11-30 01:19:03
【问题描述】:

我正在使用带有 FormsAuthentication 的 WCF REST。这种身份验证模式使用HTTP 302 Found 覆盖HTTP 401 Unauthorized 响应状态,该状态会像在Web 应用程序中一样重定向到“登录网址”。

当然,这在 WCF REST 应用程序中没有意义,我想确保 401 状态到达请求者。

我试过这样做:

        var response = WebOperationContext.Current.OutgoingResponse;
        response.StatusCode = HttpStatusCode.Unauthorized;
        HttpContext.Current.Response.SuppressContent = true;
        HttpContext.Current.Response.StatusCode = 401;
        HttpContext.Current.Response.End();

但是当这些行被执行时,我的客户端调用中出现异常:

System.Net.WebException occurred
  Message=The underlying connection was closed: An unexpected error occurred on a receive.
  Source=System
  StackTrace:
       at System.Net.HttpWebRequest.GetResponse()
       at RestPrototype.Web.Infrastructure.Http.ByPassGet(HttpContextBase httpContext, Uri url) in D:\TFS Source\PROTOTYPE\RestPrototype.Web\Infrastructure\Http.cs:line 165
  InnerException: System.IO.IOException
       Message=Unable to read data from the transport connection: The connection was closed.
       Source=System
       StackTrace:
            at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
            at System.Net.HttpWebRequest.MakeMemoryStream(Stream stream)
       InnerException: 

在 Fiddler 上我可以看到 401 已发送:

HTTP/1.1 401 Unauthorized
Cache-Control: private
Transfer-Encoding: chunked
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 03 Oct 2011 15:22:41 GMT

Transfer-Encoding: chunked 和另一方在不发送正文的情况下关闭连接,导致客户端出现异常。不幸的是,我不知道如何避免该标头并放置 Content-Length: 0,因为 ASP.NET 会覆盖它。

我想以 WCF 风格解决这个问题,如果可能的话,不使用自定义 HttpModule。如果有人知道防止 ASP.NET 覆盖我的标头的方法,我们将非常欢迎。

问候。

【问题讨论】:

    标签: asp.net http forms-authentication wcf-rest


    【解决方案1】:

    您必须通过您的 web.config 表明不需要当前用户来访问特定的路由/url。使用“位置”标签:

    ...
    </system.web>
    <location path="/MyWCFEndpoint">
        <system.web>
            <authorization>
                <!-- override default authentication settings -->
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>
    

    【讨论】:

    • 不幸的是,这并没有改变任何东西,同样的行为正在发生。
    • 我唯一可以推荐的是尝试不带前导斜杠的“路径”属性,并确保您的位置标签紧跟在您的主要 system.web 部分之后
    猜你喜欢
    • 2011-11-23
    • 2014-01-08
    • 2018-08-15
    • 1970-01-01
    • 2021-01-16
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多