获取当前请求的凭据以在WebRequest中使用

时间:2008-12-10 09:34:39

标签: asp.net asp.net-mvc

访问我的网站时,用户必须输入其凭据。它们基本上是普通的目录访问凭证。 在某一点上,我通过调用

检查他们想要下载的某个文件是否存在
WebRequest req = HttpWebRequest.Create(checkUri.AbsoluteUri);
WebResponse res = req.GetResponse();

虽然我可以从浏览器访问checkUri,但在进行上述检查时我得到401。我想我必须设置

req.Credentials

但我不知道当前凭据的存储位置......

有什么想法吗?

- 更新 -

  • 集成Windows身份验证:否
  • 允许匿名:关闭
  • Caler:同一网站页面上的链接(GET)
  • 模仿:默认为关闭(甚至不知道如何在asp.net mvc中启用它)

3 个答案:

答案 0 :(得分:6)

我在使用表单身份验证的网站上遇到了类似的问题,我能够通过使用提供的代码here作为线程中的第二个回复来解决此问题。

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
// Add the current authentication cookie to the request
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(
    FormsAuthentication.FormsCookieName,
    cookie.Value,
    cookie.Path,
    HttpContext.Current.Request.Url.Authority);

req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(authenticationCookie);

WebResponse res = req.GetResponse();

答案 1 :(得分:5)

我想你想要这个:

req.Credentials = CredentialCache.DefaultCredentials;

答案 2 :(得分:1)

您将需要启用集成Windows身份验证。

我不知道ASP.NET MVC会发生什么,但是在ASP.NET Web Forms中,模拟开启了:

<identity impersonate="true"> 
web.config中的