Keep the content-type in sync

by Mads Kristensen 23. January 2007 00:44

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.

> * Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

1/31/2007 5:20:22 AM #

 Clinton Gallagher

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?

Clinton Gallagher |

2/2/2007 6:50:06 PM #

Richard

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.

Richard |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008