Keep the content-type in sync

Jan 22, 2007

Most websites include a meta-tag that tells the browser what content-type the document is. It looks like this:

<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" />>

All ASP.NET web applications also adds the content-type to the HTTP headers of the response by default and to avoid surprises you should make sure the header and meta-tag inform the browser about the same content-type.

You can specify the content-type on individual pages or globally in the web.config like so:

<globalization responseEncoding="UTF-8" requestEncoding="UTF-8" />

To avoid giving the browser two different content-types you can use this little method and put it in the master page.

private void AddMetaContentType()

{

  HtmlMeta meta = new HtmlMeta();

  meta.HttpEquiv = "content-type";

  meta.Content = Response.ContentType + "; charset=" + Response.ContentEncoding.HeaderName;

  Page.Header.Controls.Add(meta);

}

It will add a meta-tag that specifies the same content-type as the HTTP header does. That way you just have to change the encoding in the web.config and it will automatically change the meta-tag accordingly.

>* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!

Comments (2) -

 Clinton Gallagher
Clinton Gallagher
1/30/2007 8:20:22 PM #

Hey MadMan nice work but...

... reading the HTML source of your blog shows your meta tags nice and readable each on its own line. My use of the HtmlMeta class results in one great big mass of difficult to read text all mashed together.

Can you show us (me) how to use the HtmlMeta class to achieve the nice neat readable HTML source when writing into the HTML head element?

Richard
Richard
2/2/2007 9:50:06 AM #

The Encoding.HeaderName property is generally used in email; for HTML content, you should use the Encoding.WebName property. Alternatively, you can use Response.CharSet property.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.