Search code examples
c#httpresponsehttp-response-codespushstreamcontent

HttpResponse - how to set status code depends on PushStreamContent execution result


I write data to http response using PushStreamContent class. I need to retrieve an appropriate HTTP status code depends on result of onStreamAvailable delegate execution. Here is an example code:

[HttpGet]
public HttpResponseMessage Get(int id)
{
    try
    {
        HttpResponseMessage response = this.Request.CreateResponse();
        response.Content = new PushStreamContent((Stream outputStream, HttpContent content, TransportContext context) =>
        {
            try
            {
                throw new Exception("Just an exception");

                response.StatusCode = HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                using (StreamWriter sw = new StreamWriter(outputStream))
                {
                    sw.WriteLine(ex.Message);
                    sw.Flush();
                }

                response.StatusCode = HttpStatusCode.InternalServerError;
            }
        });

        return response;
    }
    catch (Exception ex)
    {
        return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
    }
}

The example above always retrieves status code 200 (Ok). How I can fix it?


Solution

  • You cannot fix it within the PushStreamContent action. By the time you get to the point where you are setting the status code, you have already started sending the response, and thus have already sent a 200. This is a drawback of PushStreamContent.