我仅使用一种中间件运行WebAPI,并且添加Content-Length标头时无法设置响应HTTP状态代码。 带Content-Length标头的状态码默认为200 OK(与长度无关,为零或非零)。 如果我不添加Content-Length标头,则设置状态代码会很好。
我正在使用OnSendingHeaders()并能够在响应中添加标头并设置响应主体,但是设置状态不起作用。
为什么Content-Length标头会干扰状态码?谢谢!
我将这个问题发布为我创建的其他线程(OWIN Middleware not able to set http status code)的后续内容。创建此新线程以提高可见性。
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)
{
await ProcessIncomingRequest();
context.Response.OnSendingHeaders(state =>
{
var cntxt = (IOwinContext)state;
SetResponseMessage(cntxt);
}, 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" });
//Status code is not getting set and default to 200 OK when I add Content-Length header
//Without Content-Length header, setting response http status code works
context.Response.Headers.Add("Content-Length", new[] { string.Format("{0}", _responseBody.Length) });
//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";
}
}