session - 在中间件中使用 .NET Core Session

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

当我在 .NET Core 中编写使链短路并返回响应的中间件时,它不会设置 session 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 中的相关代码类(class):

public class Startup
{

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

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

传递时的响应 header :
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

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

最佳答案

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

关于session - 在中间件中使用 .NET Core Session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48330467/

相关文章:

c# - Azure DevOps Pipeline 构建失败,因为它可以创建文件夹来写入 XML 文档文件

c# - 在哪里可以找到有关为 Microsoft 扩展日志记录配置日志记录设置的文档?

model-view-controller - 在自定义中间件中访问 TempData

asp.net-core - 在中间件中获取异常

angular - 如何将 SPA 嵌入 ASP.NET Core 库并从路径提供服务

node.js - NodeJS : What's the best way to share session between server-rendered views and React app

jsf - 如何在 JSF 托管 bean 中创建、访问和销毁 session ?

带有不完整对象的 PHP session

java - session在几个servlet之间是否存在同步问题?

.net - 在.NET Core中找不到ElasticSearch Nest客户端