开发者

ASP.NET MVC: files containing extension methods inside App_Code must have Build Action "None"?

开发者 https://www.devze.com 2023-01-06 03:49 出处:网络
This seems to be the only thing that works: If a .cs file is inside App_Code... And does not contain extension methods: set the build action to \"Compile\"; otherwise no other source code in the p

This seems to be the only thing that works:

  • If a .cs file is inside App_Code...
    • And does not contain extension methods: set the build action to "Compile"; otherwise no other source code in the project knows of its existence.
    • And contains extension methods: set the build action to "None"; otherwise you get an error that the reference to x.Foo is ambiguous between MyExtensions.Foo and MyExtensions.Foo.
  • If a .cs file is outside App_Code, inside a folder called Helpers, it must have build action set to "Compile," regardless of whether or not it contains extension methods.

I don't understand this behavior. I wasn't su开发者_运维问答re that ASP.NET MVC contained any special privileges for App_Code, but it looks like it does... but only in the sense that it auto-compiles extension-method containing .cs files, even when the build action is set to "None"?? Someone please explain.


I'm assuming you've created a Web Application Project, not a Web Site Project. The App_Code folder in an ASP.NET application is special. It is designed to allow you to drop in code to have it compiled with the website in place. Because of this, the project items are marked as "None" to make sure they are not compiled by Visual Studio. When you publish a Web Site Project to your hosted environment, the code files themselves are copied in the App_Code folder, and this is compiled into a seperate assembly by the ASP.NET runtime.

Now, when you create an MVC Web Application, you must remember that it is not the same project type as a Web Site Project. An MVC Web Application will compile locally to an assembly in your /bin directory. If you add an App_Code folder to your project with your code in and you change the Build type to Compile, you run into problems because:

  1. Your MVC application has compiled and includes a MyExtensions.Foo type and,
  2. ASP.NET is compiling the App_Code folder which also has a MyExtensions.Foo type.

My recommendation is to avoid using App_Code. I tend not to, as I favour a more concise project structure. Use the Models folder for code, or create other folders.....

If you really want to use an App_Code folder, it might be better to mark the build action of any of the files as "Content" to ensure they are copied to the output directory when publishing your site.

0

精彩评论

暂无评论...
验证码 换一张
取 消