如果 ASP.NET Core 中的 cookie 正确,如何验证 cookie 然后重定向到主页或输入的 URL?

How do I authenticate a cookie and then redirect to the homepage or the inputted URL if the cookie is correct in ASP.NET Core?

逻辑相当原始 - 如果用户访问页面但没有 cookie,这表明用户 accepted/denied cookie 他被重定向到 cookie 接受页面。当他设置 cookie 时,他会被重定向到之前输入的 URL 或主页(取决于用户输入的 URL)。

我如何在 ASP.NET Core 中实现这一点(如果重要的话,我正在使用 .NET 6)

我的伪代码如下所示:

[Route("/*")]
var result = AuthenticateCookie(document.cookie("banneracceptance", true).authenticate());
if (result === true)
Redirect(/Homepage || inputtedURL);
else
throw new Error ("Wrong credentials");

显然我是 C# 的初学者,所以我用 JavaScript 风格编写了它。

P.S。我在哪个组件中编写此逻辑?控制器? Startup.cs?

这最好通过对所有请求使用一些自定义中间件来解决。你把它放在管道中,然后检查 cookie,如果它不存在或与我们想要的值不匹配,则重定向。也许还检查它请求的页面,但管道似乎足够聪明,不会让您进入重定向循环。

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>();
    }
}

然后在你的startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...

    app.UseCookieCheckMiddleware();

    ...
}

请注意,您放置中间件调用的位置也会进入请求管道,因此请确保在配置方法中重要的内容位于它的前面,而依赖于重定向的内容位于它之后。