从控制台应用程序请求MVC页面,传入包含FormsAuthentication cookie的上下文

Lei*_*ers 6 c# pdf asp.net-mvc azure

我有一个控制台应用程序(最终将作为Azure中的工作程序运行)从主ASP.Net MVC站点请求页面,并将其转换为PDF.该站点由表单身份验证保护.

在请求页面的代码中,我传入一个包含有效表单身份验证cookie的HttpContext:

byte[] pdfBytes = PdfHelper.UrlToPdfBytes(url, new HttpContextWrapper(GetHttpContext(url)));
Run Code Online (Sandbox Code Playgroud)

和GetHttpContext方法:

private static HttpContext GetHttpContext(string url)
{
    var stringWriter = new StringWriter();

    var httpRequest = new HttpRequest("", url, "");
    var httpResponse = new HttpResponse(stringWriter);

    var httpContext = new HttpContext(httpRequest, httpResponse);

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        2,
        "remoteuser",
        DateTime.Now,
        DateTime.Now.AddMinutes(5),
        false,
        String.Empty,
        FormsAuthentication.FormsCookiePath);

    // Encrypt the ticket.
    string encryptedTicket = FormsAuthentication.Encrypt(ticket);

    // Create the cookie.
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
    {
        HttpOnly = true//,
        //Domain = new Uri(url).Host
    };

    httpRequest.Cookies.Add(cookie);

    return httpContext;
}
Run Code Online (Sandbox Code Playgroud)

不过,无论我尝试什么,生成的PDF总是包含登录表单 - 认证cookie似乎被忽略了.

cookie名称是相同的,里面的值与浏览器中存在的cookie匹配,但我无法使其工作.

我的控制器操作上的属性甚至没有被命中(我有一个确保登录用户可以访问所请求的数据),这表明它是将请求丢弃到登录表单的IIS(通过Web中的设置)的.config).

我通过在控制器上添加AllowAnonymous属性获得了工作请求,因此我知道请求本身按预期工作,但我无法使FormsAuthentication方面工作.我目前只在VS2017本地工作,使用IIS(不是IIS Express).

我在PDFHelper.UrlToPdfBytes方法中设置了断点,并且cookie在那里(并且票证正确解密).

这几天我一直很沮丧,所以任何帮助都表示赞赏.

小智 0

FormsAuthentication.Encrypt使用 machine.config 中执行此控制台应用程序的键。

相反,您可以尝试使用 HttpRequest/Response 进行“登录”,并使用您收到的 cookie 来响应您的“pdf”请求。