我正在尝试编写一个调用下一个中间件的中间件,然后该中间件的响应主体是什么,它将由我的中间件进行更改。
这是Configuration()
类中的Startup
方法的样子:
public void Configuration(IAppBuilder app)
{
app.Use<OAuthAuthenticationFailCustomResponse>();
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
这是我写的中间件:
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);
}
}
}
但是,调用API后,我仍然收到OAuthBearerAuthentication
中间件的响应,即:
{ “消息”:“对此请求的授权已被拒绝。” }
This是我学习编写更改响应正文的代码的地方;
答案 0 :(得分:0)
原始流没有放回上下文响应正文中
public async override Task Invoke(IOwinContext context) {
// hold a reference to what will be the outbound/processed response stream object
var stream = context.Response.Body;
// create a stream that will be sent to the response stream before processing
using (var buffer = new MemoryStream()) {
// set the response stream to the buffer to hold the unaltered response
context.Response.Body = buffer;
// allow other middleware to respond
await Next.Invoke(context);
// we have the unaltered response, go to start
buffer.Seek(0, SeekOrigin.Begin);
// read the stream from the buffer
var reader = new StreamReader(buffer);
string responseBody = reader.ReadToEnd();
//...decide what you want to do with the responseBody from other middleware
//custom response
var byteArray = Encoding.ASCII.GetBytes("Hello World");
//write custom response to stream
stream.Write(byteArray, 0, byteArray.Length);
//reset the response body back to the original stream
context.Response.Body = stream;
context.Response.StatusCode = 200;
context.Response.ContentLength = byteArray.Length;
}
}