【发布时间】:2018-01-30 06:02:39
【问题描述】:
如果用户在访问特定 URL 时未经过身份验证/授权,我们会尝试将用户(使用返回 URL)重定向到登录页面。但是,在将用户重定向到登录页面时,我们无法在路由中添加自定义参数(在这种情况下为客户端名称)。我们正在使用 asp.net 身份核心框架。
在 Startup.cs 中,我们定义了以下适用于所有人的路由。
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Edge",
template: "{clientname}/{controller}/{action}");
});
还在代码行下方添加以确保所有 URL 都需要身份验证
services.AddMvc(o =>
{
o.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
})
并配置IdentityOptions重定向到登录页面如下
services.Configure<IdentityOptions>(opt =>
{
opt.Cookies.ApplicationCookie.LoginPath = new PathString("/Account/Login");
});
在下面的帐户控制器中是登录方法
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
this.ViewData["ReturnUrl"] = returnUrl;
return View();
}
如果用户试图访问任何未经身份验证的 URL,它应该重定向到登录页面。下面以 Home Controller 中的 Index 方法为例。
public IActionResult Index()
{
return View();
}
但是,每当我们尝试将用户重定向到登录页面时,它都不会在 URL 中附加客户端名称。它在/Account/Login 中缺少客户端名称的 URL 下方形成
http://localhost:5002/Account/Login?ReturnUrl=/ClientA/home/index
因此,导致 404 Page not found 错误。那么我们需要做些什么来正确重定向。
Url 格式如下
http://localhost:5002/ClientA/Account/Login?ReturnUrl=/ClientA/home/index
【问题讨论】:
-
你能把整个 routeconfig.cs 贴出来
-
我正在使用 asp.net 核心,其中 routeconfig.cs 不存在。我们在 Startup.cs 文件中定义了我在代码中提供的路由
标签: c# asp.net-mvc asp.net-core asp.net-core-mvc asp.net-identity