我有以下代码:
public class CookieCheckMiddleware
{
private readonly RequestDelegate _next;
public CookieCheckMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if(httpContext.Request.Cookies["MyCookie"] == null && httpContext.Request.Path != "/WhereIShouldGo")
{
httpContext.Response.Redirect("/WhereIShouldGo");
}
await _next(httpContext); // calling next middleware
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CookieCheckMiddlewareExtensions
{
public static IApplicationBuilder UseCookieCheckMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CookieCheckMiddleware>();
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCookieCheckMiddleware();
...
}
如果没有设置cookie,它基本上会重定向到强制门户。现在我需要提高一个级别-我需要以某种方式保存httpContext.Request.Path并在用户接受cookie后立即转发到它。所以事先设置一个cookie不是一个选项,因为用户还没有接受它…我怎么才能做到呢?
解决方案是通过这样的重定向给出请求URL:httpContext.Response.Redirect("/Cookies?q="+ httpContext.Request.Path);
然后通过JavaScript获取GET参数并在点击按钮后重定向。
结案:-)