开发者

Prevent FormsAuthentication from overriding the response status in WCF REST

开发者 https://www.devze.com 2023-04-10 13:58 出处:网络
I am using WCF REST with FormsAuthentication. This authentication mode, overrides the HTTP 401 Unauthorized response status with a HTTP 302 Found that redirects to the \"login Url\" like in a web appl

I am using WCF REST with FormsAuthentication. This authentication mode, overrides the HTTP 401 Unauthorized response status with a HTTP 302 Found that redirects to the "login Url" like in a web application.

Of course that doesn't make sense in a WCF REST Application, and I would like to ensure that the 401 status arrives to the requester.

I have tried doing this:

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

But when that lines are executed, I get an exeption in my client side call:

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 Re开发者_如何学GostPrototype.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: 

On Fiddler I can see that the 401 is sent:

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

That Transfer-Encoding: chunked and the other side closing the connection without sending the body, is causing that exception in the client side. Unfortunately I don't know how to avoid that header and put a Content-Length: 0, since ASP.NET overrides it.

I would like to solve this in a WCF style, without use a custom HttpModule if possible. And if somebody know a way to prevent ASP.NET from overriding my headers will be very welcomed.

Regards.


You have to indicate via your web.config that no current user is needed to access a particular route/url. Use the "location" tag:

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

精彩评论

暂无评论...
验证码 换一张
取 消