Domanda

I'm in the process of creating a REST API using HttpListener in .NET (C#). This all works out great, except for one slight issue.

I'm trying to return responses with Status Codes other than OK (200), for instance ResourceNotFound (404).

When I set the StatusCode of the HttpListenerResponse to something other than 200, and create a response body (using HttpListenerResponse.OutputStream), it seems to be resetting the status code to 200. I'm not able to send a response with StatusCode 404 and a message body. However, this should be possible according to the HTTP specs. I'm checking the requests and responses with Fiddler, but I'm not able to get what I'm looking for.

È stato utile?

Soluzione

I've had the same problem and found the source of the problem :

If you write the body in the OutputStream before set the StatusCode (or any other property), the response will be sent before the modification is applied !

So, you have to proceed in this order :

public void Send(HttpListenerContext context, byte[] body)
{
    // First, set a random status code and other stuffs
    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    context.Response.ContentType = "text/plain";

    // Write to the stream IN LAST (will send request)
    context.Response.OutputStream.Write(body, 0, body.Length);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top