我正在尝试在我的Web Api中实现Antifrogery Token,但却出现以下错误:
名称' AntiForgery'在当前背景下不存在。
这是我的代码:
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace MyAPI
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateAntiForgeryTokenAttribute: FilterAttribute
{
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
try
{
string cookieToken = "";
string formToken = "";
//I am getting error on the line written below for "AntiForgery":
AntiForgery.Validate(cookieToken, formToken);
}
catch
{
actionContext.Response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.Forbidden,
RequestMessage = actionContext.ControllerContext.Request
};
return FromResult(actionContext.Response);
}
return continuation();
}
private Task<HttpResponseMessage> FromResult(HttpResponseMessage result)
{
var source = new TaskCompletionSource<HttpResponseMessage>();
source.SetResult(result);
return source.Task;
}
}
}
答案 0 :(得分:1)
命名空间System.Web.Helpers存在于某个程序集中。
您必须将System.Web.WebPages程序集添加到项目中,然后添加一个新的using语句,如下所示:
解决方案资源管理器 - &gt; [项目] - &gt;参考文献 - &gt; (右键单击)添加参考... - &gt;扩展程序(标签) - &gt; System.Web.WebPages - &gt;添加
using System.Web.Helpers;
答案 1 :(得分:1)