“WebSecurity” does not exist in the current contex

2019-07-26 03:57发布

问题:

I am getting the following compilation error:

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS0103: The name 'WebSecurity' does not exist in the current context

Source Error:


Line 1:  @{
Line 2:      if (!WebSecurity.Initialized)
Line 3:      {
Line 4:          WebSecurity.InitializeDatabaseConnection("AreaProject", "User", "UserId", "EmailAddress", autoCreateTables: true);

Source File: c:\Projects\area\trunk\dotNet\area.Web\area.Web\_AppStart.cshtml    Line: 2 
enter code here

My project is correctly referencing to "System.Web" and my other files that are using " System.Web.Security" are compiling fine.

The problem started when I added the references System.Web, System.Web.Pages and System.Web.Razor to my application. But I didn't make any change to WebMatrix.WebData or WebMatrix.Data.

回答1:

The WebSecurity class that is being referenced here is apart of WebMatrix.WebData and not System.Web or System.Web.Security. You probably need to add a reference to WebMatrix.WebData.dll and things should at least get past the runtime compiler error.

You get the compiler error at runtime because views are normally compiled when the application starts up for the first time, instead of when the assemblies are complied.



回答2:

I'm assuming you are trying to run the MVC4 application first time.

MVC4 adds boatload of assembilies for Internet Application template. It becomes PIA to remove them if you do not use it.

Basically, if you do not use WebMatrix or OAuth to authenticate, you can just comment out everything inside SimpleMembershipInitializer class.

private class SimpleMembershipInitializer
{
  // Comment out everything
}

Just for testing, you can also comment out every line inside AccountController that throw exception.



回答3:

Old thread, but just in case it helps someone down the road. I am not sure why it works this way, but sometimes installing packages like WebMatrix.WebData, WebMatrix.Data is not enough. When I look at the Reference section of my application after these assemblies were installed, WebMatrix.WebData, WebMatrix.Data were still not showing up there, although they were in the BIN folder of the application. I had to literally use Add Reference to make them. Only then, they shown up and everything started working.