public class MyMiddleware
{
RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
//await context.Response.WriteAsync("Hello!");
await _next(context);
context.Response.Headers.Add("X-ElapsedTime", new[] { "bla" });
}
}
As soon as I add something like a header. I cannot receive any more the response from my Web API controller.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMyMiddleware();
app.UseMvc();
}
Do I need to read first the answer the following middleware "UseMvc" produced?
I just have a very simple Controller method:
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
//Task t = new Task(() => Thread.Sleep(2000));
//t.Start();
return new string[] { "value1", "value2" };
}
I think I found a solution, but it is not actually a full answer:
public class MyMiddleware
{
RequestDelegate _next;
HttpContext _context;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
_context = context;
context.Response.OnStarting(OnStartingCallback, state: this);
await _next(context);
}
public Task OnStartingCallback(object state)
{
_context.Response.Headers.Set("x-bla", "bla");
return Task.FromResult(0);
}
}
I found a reference to: https://github.com/aspnet/Session/blob/master/src/Microsoft.AspNet.Session/SessionMiddleware.cs and tried to build my code according to it.
Anyway this code feels not very safe. Is it really thread safe.