Converting CodeFile to CodeBehind

user798080 picture user798080 · May 2, 2012 · Viewed 12.1k times · Source

So I seem to have some difficulties with making my CodeFile reference into CodeBehind. Before you ask, I do not have Visual Studio and I'm not on Windows. The code is being hosted on an IIS server that I have access to.

<% @Page Language="C#" Inherits="corn.cheese.pies.CasLogin" CodeFile="anon.cs" %>

This code works perfectly, however upon changing it to:

<% @Page Language="C#" Inherits="corn.cheese.pies.CasLogin" CodeBehind="anon.cs" %>

The page returns an error:

Parser Error Message: Could not load type 'corn.cheese.pies.CasLogin'.

Answer

Michael Edenfield picture Michael Edenfield · May 2, 2012

Are you sure you understand the difference between CodeFile and CodeBehind? See, for example, CodeFile vs CodeBehind (ignore the accept answer, though, both links are dea) or this article about the difference.

In a nutshell:

A CodeBehind file is assumed to be compiled into an assembly that is deployed in the bin folder of your web site. When the ASP.NET engine loads your aspx file, it uses the Inherits directive to try to find that class. The CodeBehind file is primarily used to aid compiling (and tooling, e.g. "View Source") but the work is done at compile time.

A CodeFile file is located and compiled by ASP.NET at runtime, on demand. You can "pre-compile" your web site to fall back on the older model, which is useful if you won't want to deploy your source code to every web site. But by default, your CodeFile file is a .cs file that is deployed to the site, and the class is generated in the ASP.NET temporary storage folder. (From a technical perspective: CodeFile pages are partial class definitions, with only the custom code-behind part of the class actually deployed in the C# file; this is why CodeFile didn't exist initially, because the C# compiler could not initially do partial classes.)

By changing from CodeFile to CodeBehind you are telling ASP.NET to ignore the presence of the C# file, and only look for it in the compiled assembly. ASP.NET is, in turn, telling you that the compiled assembly doesn't actually contain the class you told it to look for.