基于丹尼尔的回答,我的代码更改为
[HttpPost]
[AllowAnonymous]
[IgnoreAntiforgeryToken]
public ActionResult Index()
{
if (!User.Identity.IsAuthenticated)
{
return NewIndex();
}
// rest of action
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult NewIndex()
{
// body of new action
}
另一种选择,基于docs draft,是注入Antiforgery
作为一种服务。
Project.json
"Microsoft.AspNetCore.Antiforgery": "1.0.0"
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery)
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery();
...
然后验证上控制器。
public class MyController : Controller
{
private readonly IAntiforgery _antiforgery;
public AccountController(IAntiforgery antiforgery)
{
_antiforgery = antiforgery;
}
public ActionResult Index()
{
if (!User.Identity.IsAuthenticated)
{
await _antiforgery.ValidateRequestAsync(HttpContext);
}
// rest of action
}
}