have followed through some samples and creating a new buffer MemoryStream
to replace the Response.Body
before calling next().
Below is my middleware :
public class TrackingMiddleware
{
private readonly AppFunc next;
public TrackingMiddleware(AppFunc next)
{
this.next = next;
}
public async Task Invoke(IDictionary<string, object> env)
{
IOwinContext context = new OwinContext(env);
// Buffer the response
var stream = context.Response.Body;
var buffer = new MemoryStream();
context.Response.Body = buffer;
await this.next(env);
buffer.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(buffer);
string responseBody = await reader.ReadToEndAsync();
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(stream);
}
}
the responsBody is always empty, event my ApiController's Action returned List of data.
Below is my Owin Startup class (Did i miss out anything ? )
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
static Startup()
{
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new OAuthAppProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
AllowInsecureHttp = true
};
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerTokens(OAuthOptions);
app.Use<TrackingMiddleware>();
}
}
Below is my ApiController
public class TestController : ApiController
{
public IHttpActionResult Get()
{
return Json(new string[] {"123", "asdfsdf"});
}
}
and My Web api configuration is registered through Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
Is this the reason that messed up the sequence of the middleware?
Alternatively, if i use MVC method and it works with the HttpContext.Current.Response
by referencing following sample