Reference to type 'HttpContextBase' claims

2019-08-23 10:24发布

I'm getting a really weird error that I've only found a few times with some pretty extensive googling. I'm making an authorization attribute to add onto my Actions in an ASP.NET MVC project in a class library. I installed the ASP packages through NuGet and can use intellisense to get the HttpContext from the filterContext, but it's saying that the HttpContext type can't be found where it's supposed to be.

Reference to type 'HttpContextBase' claims it is defined in 'System.Web' but it could not be found.

There's a few versions of this on StackOverflow, but none of them worked for me, as most of them consisted of restarting Visual Studio or just building the project.

EDIT

using System.Web.Mvc;
namespace Foo
{
    public class RequireLogin : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.Cookies)
            {

            }
        }
    }
}

The error is on HttpContext on the if statement.

1条回答
叼着烟拽天下
2楼-- · 2019-08-23 11:12

I was getting the same error in a rather simple Web Pages application that consisted of a single .cshtml page, which was doing absolutely nothing ("Hello World"). In my case the the error was a result of an incorrect .NET version being referenced.

Apparently, if you just create a rudimentary web.config and index.cshtml from scratch, .NET version 2 is referenced by default and therefore HttpContextBase is not defined.

Change the target version to .NET 4.x and the problem is resolved.

The simplest web.config I was able to get it to work with is:

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <add value="index.cshtml"/>
      </files>
    </defaultDocument>
  </system.webServer>
  <system.web>
    <compilation targetFramework="4.6.2" debug="true"/>
  </system.web>
</configuration>

In summary, check your .NET target version. It most likely is incorrect.

查看更多
登录 后发表回答