TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.NET Set ContentType

This C# article shows how the ContentType property in ASP.NET works. ContentType changes the Content-Type: HTTP header.

ContentType sets an HTTP header. It is useful when sending a response that is not HTML.

By using the ContentType property we change the HTTP header for the response. This improves compatibility in the browser.

Example. This example introduces the Global.asax.cs file. In this class, the Application_BeginRequest event handler is defined. In Application_BeginRequest, we acquire the HttpResponse, and then assign the ContentType property to "text/plain".

Finally: We write some characters with the Response.Write method and call CompleteRequest.

Response.Write

Global.asax.cs with BeginRequest method: C#

using System;
using System.Web;

namespace WebApplication1
{
    public class Global : HttpApplication
    {
	void Application_BeginRequest(object sender, EventArgs e)
	{
	    // Get response.
	    HttpResponse response = base.Response;

	    // Set ContentType.
	    response.ContentType = "text/plain";

	    // Write string.
	    response.Write("PLAIN TEXT");

	    // Complete request.
	    base.CompleteRequest();
	}
    }
}

When this is executed successfully, you will see a plain text page in your web browser with the PLAIN TEXT in monospaced font. If the response were sent as text/html, the font would most likely be serif.

HTTP headers. So when you set the ContentType property, how does this affect the HTTP headers sent by IIS? If you inspect the page's headers, you will see this line of text being sent: "Content-Type: text/plain".

And: Browsers will read this header and then display your page as a plain text document, not HTML.

Summary. We sent a different Content-Type HTTP header in the ASP.NET environment. By assigning to the ContentType property, the response will be sent with your specified value. This is useful for images, plain text and HTML.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf