ASP.NET: Keep the Content-type in Sync

    January 23, 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;



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.



Reddit | Furl

Bookmark WebProNews:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.