简体   繁体   English

如果存在cookie,则重定向到特定的URL

[英]Redirect to specific URL if cookie exists

I'm currently trying to go to specific URL if the cookie exist. 如果Cookie存在,我目前正在尝试转到特定的URL。

For example 例如

/ANYCONTROLLER/ANYMETHOD to /CONTROLLER2/METHOD2

Currently my Authentication cookie is configured like this : 目前,我的身份验证Cookie的配置如下:

 app.UseCookieAuthentication(new CookieAuthenticationOptions
 {
     AuthenticationScheme = "AmcClientCookie",
     AutomaticAuthenticate = true,
     AutomaticChallenge = true,
     LoginPath = new Microsoft.AspNetCore.Http.PathString("/Public/Home"),
     CookieSecure = hostingEnvironment.IsDevelopment()
                  ? CookieSecurePolicy.SameAsRequest
                  : CookieSecurePolicy.Always,
     ExpireTimeSpan = TimeSpan.FromDays(1)
 });

I tried to do it in a custom authorization handler but I do not have access to HttpContext . 我试图在自定义授权处理程序中执行此操作,但是无法访问HttpContext

So I tried to do it in a Action Filter but it seems that I do not have access to the Authentication to know or not if the user is connected. 因此,我尝试在操作筛选器中执行此操作,但似乎无法访问身份验证以了解或是否已连接用户。

If somebody have an idea. 如果有人有想法。

There may be other ways, but Middleware seems the most appropriate to this ( more info ). 可能还有其他方法,但是中间件似乎最适合此方法( 更多信息 )。

The short method : 简短的方法

On your startup.cs class, in Configure method, after app.UseMvc(...) call, add the following: 在您的startup.cs类的Configure方法中, app.UseMvc(...)调用之后,添加以下内容:

app.Use((context, next) =>
{
    if (context.User.Identity.IsAuthenticated)
    {
        var route = context.GetRouteData();
        if (route.Values["controller"].ToString() == "ANYCONTROLLER" &&
            route.Values["action"].ToString() == "ANYMETHOD")
        {
            context.Response.Redirect("/CONTROLLER2/METHOD2");
        }
    }

    return next();
});

The long method : 长方法

Create a class named UrlRewriteMiddleware.cs with the following: 使用以下命令创建一个名为UrlRewriteMiddleware.cs的类:

public class UrlRewriteMiddleware
{
    private readonly RequestDelegate _next;
    public UrlRewriteMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {

        if (context.User.Identity.IsAuthenticated)
        {
            var route = context.GetRouteData();
            if (route.Values["controller"].ToString() == "ANYCONTROLLER" &&
                route.Values["action"].ToString() == "ANYMETHOD")
            {
                context.Response.Redirect("/CONTROLLER2/METHOD2");
            }
        }

        await _next.Invoke(context);
    }
}

Create another class named MiddlewareExtensions.cs with the following: 使用以下命令创建另一个名为MiddlewareExtensions.cs的类:

public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseUrlRewriteMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<UrlRewriteMiddleware>();
    }
}

On your startup.cs class, in Configure method, after app.UseMvc(...) call, add the following: 在您的startup.cs类的Configure方法中, app.UseMvc(...)调用之后,添加以下内容:

app.UseUrlRewriteMiddleware();

You can also use 您也可以使用

context.Request.Path = "/CONTROLLER2/METHOD2";

instead of redirect, but the browser Url will not reflect the new path and will show the first path. 而不是重定向,但浏览器网址不会反映新路径,而是显示第一个路径。 If it is supposed to show an error or denied message, then perhaps Path is more appropriate. 如果应该显示错误消息或拒绝消息,则Path可能更合适。

I'm assuming that you're using the asp.net authentication channel, so you can test authentication as in the example. 我假设您正在使用asp.net身份验证通道,因此可以像示例中一样测试身份验证。 If not, you can access cookies in 如果没有,您可以访问

context.Request.Cookies context.Request.Cookies

Quick note (read comments) 快速笔记(阅读评论)

GetRouteData returns null before Mvc routing is setup. 在设置Mvc路由之前, GetRouteData返回null。 So, you must register this middleware after Mvc routing setup. 因此,您必须在设置Mvc路由后注册此中间件。

If for any reason you must do it earlier, you may access the url through request.Request.Path and parse it manually. 如果出于任何原因必须早些做,则可以通过request.Request.Path访问该URL并手动对其进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM