C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | 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.
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.