.NET HTTP Handler — How to Send Custom Response?

安稳与你 提交于 2019-12-22 09:47:46

问题


I have converted my custom (socket-based) server over to an HTTP Handler in IIS (.NET 4.0).

I have converted my client to send an HTTP GET in the proper format.

I do not want to change my client's response-handling code to parse out the HTML code. That is a pain in the rear that is also unnecessary. I do not need this server to work with a browser or be compatible with anything except my client.

So, I basically need the HTTP Handler (server) to send the response that the client expects -- without the "HTML/1.0", headers and whatnot.

I am using the HttpContext.Response.Write() method at the moment. I figure there is either a way to write raw data to the response, or a way to delete all the headers and HTML tags around the data I want to send.

Thanks in advance for any help. Dave


回答1:


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.



来源:https://stackoverflow.com/questions/7290840/net-http-handler-how-to-send-custom-response

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