阻止FormsAuthentication覆盖WCF REST中的响应状态

时间:2011-10-03 16:05:16

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

我正在使用带有FormsAuthentication的WCF REST。此身份验证模式使用HTTP 401 Unauthorized覆盖HTTP 302 Found响应状态,重定向到“登录URL”,就像在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();

但是当执行这些行时,我在客户端调用中得到一个exeption:

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覆盖我的标题的方法将非常受欢迎。

问候。

1 个答案:

答案 0 :(得分:0)

您必须通过web.config指示访问特定路由/网址不需要当前用户。使用“location”标签:

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