gpt4 book ai didi

c# - 等同于 asp.net-core 中的 AntiForgery.Validate() 的命令

转载 作者:行者123 更新时间:2023-11-30 20:33:08 26 4
gpt4 key购买 nike

在 asp.net-core 中是否存在类似于 AntiForgery.Validate(); 的命令来验证操作主体中的防伪 token ?

dotnet 4.5.1 中的代码示例:

public ActionResult Index()
{
if (!User.Identity.IsAuthenticated)
{
System.Web.Helpers.AntiForgery.Validate();
}

// rest of action
}

最佳答案

根据大牛的回答,我把代码改成了

[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 作为服务注入(inject)。

项目.json

"Microsoft.AspNetCore.Antiforgery": "1.0.0" 

启动.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery)
{
...


public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery();
...

然后在 Controller 上验证。

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
}

}

关于c# - 等同于 asp.net-core 中的 AntiForgery.Validate() 的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com