I am running WebAPI with just one Middleware and not able to set response HTTP status code.
I am using OnSendingHeaders() and able to add headers and set response body, but status code is not getting set and response always has it set as 200 OK.
I am able to set response status code in ValidateUrl(context) though. Difference is ValidateUrl(context) is called synchronously and OnSendingHeaders() would be called asynchronously after ProcessIncomingRequest() is executed.
Is HTTP status line being sent even before OnSendingHeaders() gets called?
How/where should I set response HTTP status code when incoming request is being processed asynchronously?
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.Use(typeof(SampleMiddleware));
}
}
public class SampleMiddleware : OwinMiddleware
{
private string _responseBody = null;
public SampleMiddleware(OwinMiddleware next) : base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
if (!ValidateUrl(context))
{
return;
}
context.Response.OnSendingHeaders(state =>
{
var cntxt = (IOwinContext)state;
SetResponseMessage(cntxt);
}, context);
await ProcessIncomingRequest();
await Next.Invoke(context);
}
private void SetResponseMessage(IOwinContext context)
{
//Setting status code
context.Response.StatusCode = 201;
//Setting headers
context.Response.Headers.Add("XYZ", new[] { "Value-1" });
context.Response.Headers.Add("ABC", new[] { "Value-2" });
//Setting response body
context.Response.Write(_responseBody);
}
private async Task ProcessIncomingRequest()
{
// Process request
//await ProcessingFunc();
// Set response body
_responseBody = "Response body based on above processing";
}
private bool ValidateUrl(IOwinContext context)
{
if (context.Request.Host.ToString().Equals("xyx"))
{
return true;
}
else
{
context.Response.StatusCode = 400;
context.Response.Write("Bad Request");
return false;
}
}
}