.NET HTTP Handler — How to Send Custom Response?

↘锁芯ラ 提交于 2019-12-06 04:46:13

If you are looking at this in a browser to verify, then what you may be seeing is the browsers attempt to fix your HTML for you.

For instance if I have this in my Handler:

public void ProcessRequest(HttpContext context)
{
    context.Response.Write("Hello World");
}

Then the Response Headers will look like this:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Sat, 03 Sep 2011 03:26:36 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 11
Connection: Close

The actual content of the response is simply

Hello World

You'll notice the default content type is text/html, however, you basically have full control over the response. You can clear the headers, add new ones, and set the content type accordingly:

public void ProcessRequest(HttpContext context)
{
    context.Response.ClearHeaders();
    context.Response.AddHeader("my-skillz", "being AWESOME!");
    context.Response.ContentType = "text/plain";
    context.Response.Write("Hello World");
}

Which will yield the following Response Headers:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Sat, 03 Sep 2011 03:40:14 GMT
X-AspNet-Version: 4.0.30319
my-skillz: being AWESOME!
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Content-Length: 11
Connection: Close

So there you have it. Take a look at the docs on HttpResponse so you can see all that is available to you, and you should be able to get exactly what you want out of the responses without any extra headache, and no HTML anywhere in sight.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!