当您在Visual Studio中创建一个新的Web应用程序(webform或mvc)时,会有一个后身份验证逻辑来检查查询字符串中的返回参数,然后将用户重定向到那里(如果存在):在weform-Login. aspx.cs中,您有以下内容:
protected void LogIn(object sender, EventArgs e)
{
...
switch (result)
{
case SignInStatus.Success:
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
...
}
}
}
在MVC-Account tController. cs中,您有:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
...
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
...
}
}
此外,Owin配置设置为使用cookie身份验证,它使用Microsoft.Owin.Security. Cookie.CookieAuthenticationHandler类,该类本身检查返回参数,并在存在时应用重定向:
protected override async Task ApplyResponseGrantAsync()
{
AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
bool shouldSignin = signin != null;
AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
bool shouldSignout = signout != null;
if (shouldSignin || shouldSignout || _shouldRenew)
{
...
if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
{
IReadableStringCollection query = Request.Query;
string redirectUri = query.Get(Options.ReturnUrlParameter);
if (!string.IsNullOrWhiteSpace(redirectUri)
&& IsHostRelative(redirectUri))
{
var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri);
Options.Provider.ApplyRedirect(redirectContext);
}
}
}
}
两个重定向似乎都在登录/身份验证请求期间执行。一个应用于HttpContext. Response,另一个应用于Owin重定向上下文。根据我的经验,看起来后一个重定向调用胜出,如果您在网站代码中登录后应用了特殊的重定向逻辑,这是一个问题,因为它被内置的Owin重定向覆盖。
这种重复逻辑有什么好的原因吗?这只是糟糕的设计吗?所以,如果我使用的是asp.netOwin CookieAuthentication,我应该在帐户控制器或aspx代码后面有登录后重定向代码逻辑吗?如果是这样,重定向应该应用于HttpContext. Response还是通过Owin以某种方式应用?
正如你所说,这三种重定向方式都属于不同的部分: WebForms、MVC、OWIN。它们中的每一个都可以独立使用(自托管情况下的OWIN),所以需要在每一个中做同样的事情。
然而,我不完全确定为什么最新的MVC模板需要重定向到本地
。我会采用向后兼容性——这种方法已经存在很久了。
此外,OWIN重定向不会在MVC中获胜-在我的一个应用程序中,我总是根据用户的角色重定向用户,即使有一个带有本地URL的参数,我的用户总是最终出现在控制器中指定的页面上MVC。
然而,看了OWIN源代码和重定向逻辑之后,MVC获胜似乎很奇怪。可能需要一路走下去,看看在MVC场景中会发生什么。