ContentType. This property sets an HTTP header—it is useful when sending a response that is not HTML. By using ContentType we change the HTTP header for the response.
Server headers. So when you set the ContentType property, how does this affect the HTTP headers sent by IIS? We will see this header being sent: "Content-Type: text/plain".
Example. Here 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.
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();
}
}
}
Page output. When this is executed successfully, you will see a plain text page in your web browser with the PLAIN TEXT in monospaced font.
Note Browsers will read this header and then display your page as a plain text document, not HTML.
A 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 27, 2022 (edit).