ToOptimizedResult and HTTP status code

When I use ToOptimizedResultto return a compressed response, any custom status codes that I set for the response get reset to 200.

This works as expected:

[SetStatus(HttpStatusCode.Created, "")]
public object Post(TestCompression obj)
{
    return obj; // returns "201 Created"
}

This is not true:

[SetStatus(HttpStatusCode.Created, "")]
public object Post(TestCompression obj)
{
    return Request.ToOptimizedResult(obj); // returns "200 OK"
}

public object Post(TestCompression obj)
{
    Response.StatusCode = 201;
    return Request.ToOptimizedResult(obj); // also returns "200 OK"
}

What should I do to make sure the status code in the compressed response is set correctly?

I found that it ToOptimizedResultcan return an object CompressedResult, but it does not guarantee this; I can do the following to successfully override the status code, but it feels wrong:

var optimized = Request.ToOptimizedResult(obj);
var compressed = optimized as CompressedResult;
if (compressed != null)
    compressed.StatusCode = HttpStatusCode.Created;
return optimized;
+4
source share

Source: https://habr.com/ru/post/1536975/


All Articles