I am trying to write a middleware that calls the next middleware and then whatever the response body of that middleware is, it will be changed by my middleware.
This is what the Configuration()
method in the Startup
class looks like:
public void Configuration(IAppBuilder app)
{
app.Use<OAuthAuthenticationFailCustomResponse>();
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
This is the middleware written by me:
public class OAuthAuthenticationFailCustomResponse : OwinMiddleware
{
public OAuthAuthenticationFailCustomResponse(OwinMiddleware next)
: base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
var stream = context.Response.Body;
using (var buffer = new MemoryStream())
{
context.Response.Body = buffer;
await Next.Invoke(context);
buffer.Seek(0, SeekOrigin.Begin);
var byteArray = Encoding.ASCII.GetBytes("Hello World");
context.Response.StatusCode = 200;
context.Response.ContentLength = byteArray.Length;
buffer.SetLength(0);
buffer.Write(byteArray, 0, byteArray.Length);
buffer.Seek(0, SeekOrigin.Begin);
buffer.CopyTo(stream);
}
}
}
However, I still receive the response of the OAuthBearerAuthentication
middleware after calling the API, which is:
{ "Message": "Authorization has been denied for this request." }
This is where I learnt to write the code that changes the response body;