C# 为什么set cookie仅与来自global.asax.cs的重定向一起工作?

C# 为什么set cookie仅与来自global.asax.cs的重定向一起工作?,c#,asp.net,cookies,asp.net-web-api2,httpcookie,C#,Asp.net,Cookies,Asp.net Web Api2,Httpcookie,我有一个WebApi2应用程序。站点的初始负载是加载SPA应用程序的静态内容。当我的Global.asax.cs文件如下所示时,cookie不会添加到响应中(如浏览器中的开发人员工具所示): 当我将其更改为具有查找该cookie并重定向回根页面的条件时(无论如何都要加载根页面),cookie就会显示出来(如浏览器中的开发人员工具所示)。以下是更新的Global.asax.cs,带有重定向: using System.Web.Http; using System.Web; using System

我有一个WebApi2应用程序。站点的初始负载是加载SPA应用程序的静态内容。当我的
Global.asax.cs
文件如下所示时,cookie不会添加到响应中(如浏览器中的开发人员工具所示):

当我将其更改为具有查找该cookie并重定向回根页面的条件时(无论如何都要加载根页面),cookie就会显示出来(如浏览器中的开发人员工具所示)。以下是更新的
Global.asax.cs
,带有重定向:

using System.Web.Http;
using System.Web;
using System.Security.Claims;
using System.Linq;

namespace Application
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        protected void Application_PostAuthorizeRequest()
        {
            var claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal;
            if (claimsPrincipal != null)
            {
                if (HttpContext.Current.Request.Cookies[".UIROLES"] == null)
                {
                    var cookie = new HttpCookie(".UIROLES", "admin");
                    HttpContext.Current.Response.Cookies.Add(cookie);    
                    HttpContext.Current.Response.Redirect("http://localhost/Application");
                }
            }
        }
    }
}
我曾经读过很多关于cookies和asp.net的文章,但是我不明白为什么第一个版本不起作用,第二个版本不起作用。如果我的UI应用程序需要再次访问服务器,我可以通过ApiController调用来获取数据,但在我看来,不需要额外访问服务器

更新:我在
Global.asax.cs
中尝试了许多其他“生命周期”事件。我看不出在
应用程序_AuthenticateRequest
方法之前有
HttpContext.Current.User
(这是我实际获取角色的地方),但是在这一点之后的所有方法实际上似乎都不会将cookie写入响应,除非重定向在代码中。例如,我可以在
应用程序\u BeginRequest
方法中添加仲裁(
new-HttpCookie(“foo”,“bar”)
)cookie,但
HttpContext.Current.User
当时为空

为什么这样工作?

我是否可以在不需要重定向或其他api调用的情况下让第一组代码正常工作?

using System.Web.Http;
using System.Web;
using System.Security.Claims;
using System.Linq;

namespace Application
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        protected void Application_PostAuthorizeRequest()
        {
            var claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal;
            if (claimsPrincipal != null)
            {
                if (HttpContext.Current.Request.Cookies[".UIROLES"] == null)
                {
                    var cookie = new HttpCookie(".UIROLES", "admin");
                    HttpContext.Current.Response.Cookies.Add(cookie);    
                    HttpContext.Current.Response.Redirect("http://localhost/Application");
                }
            }
        }
    }
}