【问题标题】:Using .NET Core Session in middleware在中间件中使用 .NET Core Session
【发布时间】:2018-06-28 01:36:30
【问题描述】:

当我在 .NET Core 中编写使链短路并返回响应的中间件时,它不会设置会话 cookie。一个简短的例子:

public class Middleware
{

    private RequestDelegate _next;

    public Middleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var req = context.Request;
        if (req.Path.ToString() == "/hello-world")
        {
            context.Response.StatusCode = 200;
            context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
            await context.Response.WriteAsync("Hello, world!");
            return;
        }

        await _next(context);

    }

}

这是我的Startup类的相关代码:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddDistributedMemoryCache()
            .AddSession();
    }

    public void Configure(IApplicationBuilder app)
    {
        app
            .UseSession()
            .UseMiddleware<Middleware>();
    }
}

传递的响应标头:

HTTP 200 No Error

Server: Kestrel
Set-Cookie: .AspNetCore.Session=CfDJ8C1XpX5nCrFCnHz%2BDwlF41YjVSyPMqB8Qmk6qcDPnOSpG22yun3hsXpRBgMDhlX%2ByLbqkUtqPRYY%2B1%2Bno5WeRLnabM1zBDggvB4YEg6ooBiGN%2B5ktjjgfp4uH5mmlWZpEQyQJQb0vKDGwqWpMlLEGjMxVIMqOnkqjM0DvsQIPjt6; path=/; samesite=lax; httponly
Content-Type: text/html; charset=utf-8
Pragma: no-cache
Transfer-Encoding: Identity
Date: Thu, 18 Jan 2018 20:48:55 GMT
Expires: -1
Cache-Control: no-cache

短路响应头:

HTTP 200 No Error

Transfer-Encoding: Identity
Content-Type: text/html; charset=utf-8
Server: Kestrel
Date: Thu, 18 Jan 2018 21:17:39 GMT

简而言之,我需要知道为什么会话中间件没有发回 cookie。当我加载有关无法解码 cookie 的页面时,我似乎也收到了一些会话警告。

【问题讨论】:

    标签: session .net-core asp.net-core-middleware


    【解决方案1】:

    我没有向会话中添加任何内容,因此中间件没有创建会话。只需添加 context.Session.SetString("stuff", "3");(或 Set* 变体之一)即可将会话发送到客户端。您需要在写入响应正文之前执行此操作。

    【讨论】:

    • thanx,帮了我一把。尽管按照 .net 核心文档中的指定添加/配置,但我收到一条错误消息,提示会话未启动。我添加了一个随机变量后,它就起作用了! ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多