【问题标题】:How to get the Host Request.PathBase from Startup::Configure如何从 Startup::Configure 获取 Host Request.PathBase
【发布时间】:2017-07-01 12:40:51
【问题描述】:

在我的 Startup 类 public void Configure(IApplicationBuilder app...) 中,我正在以一种非常标准的方式设置我的 cookie 身份验证:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieName = cookieName,
//CookiePath = "",
AuthenticationScheme = cookieAuthSchemeName,
}); 

但我意识到我无法按照我想要的方式设置 CookiePath,因为在这个阶段我不知道如何访问主机服务器路径库。例如,如果我的服务器正在侦听 http://internal.net:5000/myappbase/,那么我可以拥有一个具有一个操作的控制器,并且我想将我的 cookie 路径设置为 /myappbase/controller1 我没有做到这一点,因为在那个阶段,Startup::Configure,我无法获得有关服务器监听 /myappbase 的信息。也许有注入的东西我可以使用,但我还没有找到。

我尝试过的:

注入 IHttpContextAccessor contextAccessor 没有帮助。

我知道当我根据我在此处阅读的内容实际处理请求时,我可以在其他任何地方轻松获得:How can I get the root domain URI in ASP.NET?

而且我还可以看到,在 CookieAuthenticationHandler 的代码中,它是根据 Request 获取这些信息的:

protected string CurrentUri
{
    get
    {
        return Request.Scheme + "://" + Request.Host + Request.PathBase + Request.Path + Request.QueryString;
    }
}

或者

var cookieOptions = new CookieOptions
{
    Domain = Options.CookieDomain,
    HttpOnly = Options.CookieHttpOnly,
    Path = Options.CookiePath ?? (OriginalPathBase.HasValue ? OriginalPathBase.ToString() : "/"),
};

但实际上,在 Startup::Configure 中,我不知道该怎么做。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# cookies asp.net-core


    【解决方案1】:

    ConfigureServices(IServiceCollection services)方法中,添加:

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.OnAppendCookie = (e) =>
        {
            e.CookieOptions.Path = e.Context.Request.PathBase;
        };
        .....
    }); 
    

    注意:当cookie被创建并发送到客户端之前,cookie的路径将被设置为Request.PathBase。

    【讨论】:

    • 当cookie被创建并发送到客户端之前,cookie的路径会被设置为Request.PathBase
    猜你喜欢
    • 2019-04-01
    • 2023-03-18
    • 1970-01-01
    • 2011-07-05
    • 2021-02-17
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多