Reputation: 435
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.
Upvotes: 3
Views: 10159
Reputation: 419
In addition to what @Optimax said, my use case was that I was mixing up AspNetCore and Web namespaces. My project already targeted .net5
I was trying to implement a custom authorization filter attribute using:
public class ClaimRequirementFilter : IAuthorizationFilter
However, my code comprised mostly of .Net Core, so I had to use this instead:
public class ClaimRequirementFilter : IAsyncAuthorizationFilter
The constructor will now use:
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext...
//Note that HttpContext should now be valid.
/*Other Async calls*/
}
Hope it helps!
Upvotes: 0
Reputation: 1584
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.
Upvotes: 4