c# - Changing the response object from OWIN Middleware -
my owin middleware this. (framework asp.net web api).
public class mymiddleware : owinmiddleware { public mymiddleware(owinmiddleware next) : base(next) { } public override async task invoke(owinrequest request, owinresponse response) { var header = request.getheader("x-whatever-header"); await next.invoke(request, response); response.setheader("x-myresponse-header", "some value"); response.statuscode = 403; } }
questions:
is recommended practice derive
owinmiddleware
? see in katana source, of middleware classes deriveowinmiddleware
, not.i can see request headers okay. setting response header or status code after
next.invoke
in middleware has no effect on response returned client. if set response header or status beforenext.invoke
call, response headers , status set returned client. right way of setting these?
yes, deriving owinmiddleware recommended. reason middleware classes don't derive owinmiddleware either haven't switched on yet because class introduced recently. or avoid having assembly take dependency on microsoft.owin assembly reason.
the probable reason setting stuff on response after calling invoke on next doesn't work response http header gets sent starts writing response body stream. changes status code or http headers after middleware component starts writing response body won't have effect.
what can try doing use onsendingheaders callback owin provides. here's how can use it:
public override async task invoke(iowincontext context) { var response = context.response; var request = context.request; response.onsendingheaders(state => { var resp = (owinresponse)state; resp.headers.add("x-myresponse-header", "some value"); resp.statuscode = 403; resp.reasonphrase = "forbidden"; }, response); var header = request.headers["x-whatever-header"]; await next.invoke(context); }
credit biscuit314 updating answer.
Comments
Post a Comment