Using the Title property of Page requires a header control on the page, how to solve in .net(C#)

Lionsure 2020-08-22 Original by the website

In order to modify the title and keywords of webpage, they are usually displayed dynamically with code. Sometimes an exception will be thrown if the setting is improper. This kind of error is relatively rare. If you don't take a closer look, you really don't know what is going on. The specific error prompts as follows:

Using the Title property of Page requires a header control on the page (e.g. <head runat="server" />).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Using the Title property of Page requires a header control on the page. (e.g. <head runat="server" />).

Source Error: 

line 44:       KeyWords.Text = "<meta name=\"Keywords\" content=\""+ PageTitle +"\" />";
       line 46:       string description ="<meta name=\"Description\" content=\"" + PageDescription + "\" />";

There is a sentence in the error message: Using the Title property of Page requires a header control on the page. From this sentence alone, the meaning is not very obvious. If you don't look at the following "e.g. <head runat="server" />", it is really confusing. Only with this sentence did you know that the runat="server" statement indicating that the control runs on the server is missing from the head of web page, and the solution will come out after knowing the reason.

 

Solution:

Just add runat="server" to the head of webpage and the problem is solved, namely: <head runat="server">.

The <head> tag has runat="server" by default. To prevent the title of web page from wrapping, runat="server" is removed. If you still don't want title of web page to wrap, you must remove runat="server", but you can't use the control to output the title and description of web page. You can define protected member character variables in the code behind, namely:

protected string KeyWord;
        protected string Description;

After assigning values to them, output them in the foreground(aspx).