当前上下文中不存在名称为'AntiForgery'的内容。

3

我正在尝试在我的Web Api中实现防伪标记,但是遇到了以下错误:

当前上下文中不存在“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;
    }
 }
}

@Chetan Ranpariya 我正在使用那个,但问题仍然存在。 - Pranav Mishra
你确定已经包含了引用并将其添加到了 using 语句中吗? - daveBM
我已经将其添加到引用中,并使用“using System.Web.Helpers;”语句包含了命名空间。 - Pranav Mishra
AntiForgery.Validate() 似乎已经过时。不太确定这是否是问题所在:https://msdn.microsoft.com/zh-cn/library/gg568796(v=vs.111).aspx - Sujith
请问您具体添加了哪个引用? - grek40
显示剩余4条评论
2个回答

2
  1. 添加命名空间 "using System.Web.Helpers;"。
  2. 在Nuget包中安装 "Microsoft.AspNet.WebPages" 包。
  3. 将引用 "System.Web" 添加到项目中。

2

命名空间System.Web.Helpers存在于某个程序集中。

您需要将System.Web.WebPages程序集添加到您的项目中,然后添加一个新的using语句,如下所示:

Solution Explorer -> [Project] -> References -> (右键) Add Reference... -> Extensions (选项卡) -> System.Web.WebPages -> 添加

using System.Web.Helpers;

所有都正确,但请确保您使用 Version=2.0.0.0。'AntiForgery' 仅存在于此版本中。 - Serhii Matvienko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接