Ruc*_*han 10 c# asp.net asp.net-mvc antiforgerytoken
当用户登录时,然后进入登录页面.如果他再次尝试登录,则会出现Anti forgery Error.
防伪令牌无法解密.如果此应用程序由Web场或群集托管,请确保所有计算机都运行相同版本的ASP.NET网页,并且配置指定显式加密和验证密钥.AutoGenerate不能在群集中使用.
我得到的另一种错误是:
提供的防伪令牌适用于与当前用户不同的基于声明的用户.
如何处理这种防伪造错误?
DSR*_*DSR 15
创建继承HandleErrorAttribute的操作过滤器,如下例所示.然后,您可以检查请求并处理错误.
public class AntiForgeryHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
if (context.Exception is HttpAntiForgeryException)
{
var url = string.Empty;
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
var requestContext = new RequestContext(context.HttpContext, context.RouteData);
url = RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(new {Controller = "User", action = "Login"})).VirtualPath;
}
else
{
context.HttpContext.Response.StatusCode = 200;
context.ExceptionHandled = true;
url = GetRedirectUrl(context);
}
context.HttpContext.Response.Redirect(url, true);
}
else
{
base.OnException(context);
}
}
private string GetRedirectUrl(ExceptionContext context)
{
try
{
var requestContext = new RequestContext(context.HttpContext, context.RouteData);
var url = RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(new { Controller = "User", action = "AlreadySignIn" })).VirtualPath;
return url;
}
catch (Exception)
{
throw new NullReferenceException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的例子,记住你必须处理你的重定向部分取决于你的要求和要求.
然后登录
[HttpPost]
[AllowAnonymous]
[AntiForgeryHandleError]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(UserLoginViewModel model, string returnUrl)
{
//Your code...
}
Run Code Online (Sandbox Code Playgroud)
编辑评论
使用另一个控制器/动作作为AlreadySignIn()
控制器代码
public ActionResult AlreadySignIn()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
剃刀视图
@using Microsoft.AspNet.Identity
@{
ViewBag.Title = "Switch Accounts";
Layout = "~/Views/Shared/_LayoutLoginRegister.cshtml";
}
<div class="col-md-12">
<div class="block-flat text-center" style="padding: 20px; margin-bottom: 0; padding-bottom: 0;">
<i class="glyphicon glyphicon-user"></i>
<br />
<label style="padding-bottom: 10px; padding-top: 10px">You're already signed in as <strong>@User.Identity.Name</strong></label>
<label style="padding-bottom: 5px; padding-top: 5px">@Html.ActionLink("Remain signed in with this account.", "Login", "User", routeValues: null, htmlAttributes: new { id = "loginLink" })</label>
<label style="padding-bottom: 5px; padding-top: 2px">@Html.ActionLink("Click here to sign out and sign with a different account", "LogOff", "User", routeValues: null, htmlAttributes: new { id = "loginLink" })</label>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
4537 次 |
| 最近记录: |