I have a simple ASP.NET MVC site with a single controller and some actions in it. A user needs to log in to access any action (Windows Authentication, ‘Authorize’ attribue on the controller class).
When accessing the site via a browser everything works fine.
On the client, I would also like to access the site via System.Net.WebClient. I set the credentials and all actions that return a View work just fine.
But when I try to access an action that tries to make a redirect (using Controller’s Rediret() method) the server returns a 401 Unauthorized.
I’ve read about problems with WebClient and Windows authentication but the stuff I found does not seem to apply here, because everything works except for the redirects.
So after some weeks I had some time to come back to this problem and as it turns out, it has nothing to do with ASP.NET at all and it’s WebClient’s fault.
WebClient clears its credentials before following a redirect, so in this case the original request was successful but the error the occurred when WebClient tried to access the page it had been redirected to, because authentication is necessary for the target, too.
Unfortunately, you cannot just toggle this behavior via a Property. So my solution looks like this.
Instead of using WebClient, I’m using HttpWebRequest and HttpWebResponse and follow the Redirect manually. Before making the request, I set the credentials necessary to complete the request