【发布时间】:2019-10-21 19:15:57
【问题描述】:
我正在尝试在操作执行后设置一个 cookie,努力让它发挥作用。如果我从控制器而不是从中间件设置它,我设法看到了 cookie。 我玩过配置的顺序,什么都没有。 代码示例来自一个干净的 webapi 创建项目,所以如果有人想玩它很简单,只需创建一个空 webapi,添加 CookieSet 类并将 Startup 类替换为下面的类(仅添加了 cookie 策略选项)
这是我的中间件
public class CookieSet
{
private readonly RequestDelegate _next;
public CookieSet(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
var cookieOptions = new CookieOptions()
{
Path = "/",
Expires = DateTimeOffset.UtcNow.AddHours(1),
IsEssential = true,
HttpOnly = false,
Secure = false,
};
context.Response.Cookies.Append("test", "cookie", cookieOptions);
}
}
我已经添加了 p 赋值并检查了执行是否永远不会到达那里,在 Cookies.Append 行它会停止执行,所以有些事情我无法弄清楚。
这是我的 Startup 课程
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
options.HttpOnly = HttpOnlyPolicy.None;
options.Secure = CookieSecurePolicy.None;
// you can add more options here and they will be applied to all cookies (middleware and manually created cookies)
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCookiePolicy(new CookiePolicyOptions
{
CheckConsentNeeded = c => false,
HttpOnly = HttpOnlyPolicy.None,
Secure = CookieSecurePolicy.None,
MinimumSameSitePolicy = SameSiteMode.None,
});
app.UseMiddleware<CookieSet>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
我已将所有选项设置为最低要求,并使用 chrome 和 fiddler 进行了测试。
【问题讨论】:
标签: asp.net-core cookies middleware