我安装了 Microsoft.AspNetCore.Antiforgery 我的 asp.net 核心 .net 框架应用程序,添加到配置服务
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddTransient<ISession, JwtSession>(s => JwtSession.Factory());
//services.AddCors();
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services.AddMvc();
}
我想在 Controller 中使用它并按如下方式操作:
[Route("[action]"), Route("")]
[HttpGet]
public IActionResult Index()
{
var f = _antiforgery.GetAndStoreTokens(HttpContext);
return View();
}
但是不知道怎么把key放到view里。
最佳答案
我想您希望 Antiforgery 与 Ajax 场景一起工作。下面是一个例子:
在 Startup.cs 中:
// Angular's default header name for sending the XSRF token.
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
生成防伪 token cookie 的过滤器:
public class GenerateAntiforgeryTokenCookieForAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
var antiforgery = context.HttpContext.RequestServices.GetService<IAntiforgery>();
// We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
context.HttpContext.Response.Cookies.Append(
"XSRF-TOKEN",
tokens.RequestToken,
new CookieOptions() { HttpOnly = false });
}
}
过滤器的使用:
[HttpGet]
[GenerateAntiforgeryTokenCookieForAjax]
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product product)
{
关于c# - 将防伪与 Ajax 或 AngularJs 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38783976/