编程语言
首页 > 编程语言> > c# – 如何对ASP.NET MVC Web应用程序进行授权的HttpWebRequest

c# – 如何对ASP.NET MVC Web应用程序进行授权的HttpWebRequest

作者:互联网

我有一个ASP.NET MVC Web应用程序,需要允许公共API下载文件.
这是动作代码:

public ActionResult DownloadFile(int id)
{
        var item = _context.GetRepositoryFileByID(id);
        if (item == null)
        {
            return HttpNotFound();
        }
        var filePath = Path.Combine(AppConfig.FilesRepositoryStorageRoot, item.IntrenalFilePath);
        return File(filePath, "application/pdf");
}

此方法是设置了[Authorize(Roles =“Administrator,User”)]属性的控制器,因此只有登录用户才能访问此操作

现在,此操作应允许用户使用以下代码发出请求:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(fileDownloadUrl));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

我在这里缺少的是如何将授权的HttpWebRequest传递给DownloadFile操作.

我尝试的每件事都会返回登录页面,因为应用程序无法授权用户并允许他访问DownloadFile操作.

我试图使用以下代码将此Cookie值传递给请求该文件的网站

var authCookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, true);
var authCoockieValue = authCookie.Value;

然后网站使用了这个值:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(fileDownloadUrl));
request.Headers[HttpRequestHeader.Authorization] = "Bearer " + authorization;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

但是这没有用.我也尝试用“Basic”而不是“Bearer”标签传递标题,但它也是字段.

我不明白我不太了解ASP.NET MVC应用程序如何使用FormsAuthentication的[Authorize]属性,所以我谦虚地请求你的帮助……

解决方法:

我找到了解决方案.
您需要向HttpWebRequest添加身份验证Cookie,如下所示:

Uri fileDownloadURI = new Uri(fileDownloadUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileDownloadURI);
request.Headers[HttpRequestHeader.Authorization] = "Bearer " + authorization;
var authCookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, true);
Cookie requestAuthCoockie = new Cookie()
{
    Expires = authCookie.Expires,
    Name = authCookie.Name,
    Path = authCookie.Path,
    Secure = authCookie.Secure,
    Value = authCookie.Value,
    Domain = fileDownloadURI.Host,
    HttpOnly = authCookie.HttpOnly,
};
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(requestAuthCoockie);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

标签:c,asp-net-mvc,forms-authentication,httpwebrequest,asp-net-mvc-4
来源: https://codeday.me/bug/20190609/1206369.html