尝试在ASP.NET5(aka vNext)API上实现AntiForgery
我找到的所有文章都来自this article并使用System.Web.Helpers.AntiForgery.GetTokens,这不应该是ASP.NET5的方式
private static string GetTokenHeaderValue() { string cookietoken,formToken; System.Web.Helpers.AntiForgery.GetTokens(null,out cookietoken,out formToken); return cookietoken + ":" + formToken; }
是否有任何实现实际显示如何在ASP.NET5中检索这些令牌
解决方法
在Controller处生成
using Microsoft.AspNet.Mvc; using Microsoft.Framework.DependencyInjection; namespace MyApp.App.Controllers { public class MyController : Controller { public string GetAntiForgeryTokens() { var antiForgery = Context.RequestServices.GetService<AntiForgery>(); AntiForgeryTokenSet antiForgeryTokenSet = antiForgery.GetTokens(Context,null); string output = antiForgeryTokenSet.Cookietoken + ":" + antiForgeryTokenSet.FormToken; return output; } } }
在View中生成
@inject AntiForgery antiForgery @functions { public string GetAntiForgeryTokens() { AntiForgeryTokenSet antiForgeryTokenSet = antiForgery.GetTokens(Context,null); string output = antiForgeryTokenSet.Cookietoken + ":" + antiForgeryTokenSet.FormToken; return output; } } <body> @GetAntixsrftoken() </body>
验证
var antiForgery = Context.RequestServices.GetService<AntiForgery>(); antiForgery.Validate(Context,new AntiForgeryTokenSet(formToken,cookietoken));