当我在 .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的会话警告。