What's the difference among app.use
, app.run
, app.map
in Owin? When to use what? It's not straightforward when reading the documentation.
app.use
inserts a middleware into the pipeline which requires you to call the next middleware by calling next.Invoke().
app.run
inserts a middleware without a next, so it just runs.
With app.map
you can map paths, which get evaluated at runtime, per request, to run certain middleware only if the request path matches the pattern you mapped.
See docs for use
and run
and map
for more details
app.Run
The nature of Run
extension is to short circuit the HTTP pipeline immediately.
It is a shorthand way of
- adding middleware to the pipeline that does not call any other middleware which is next to it and
- immediately return HTTP response.
So, it’s recommended to use Run
extension to hook middleware at last in HTTP pipeline.
app.Use
There is a chance to pass next invoker, so that HTTP request will be transferred to the next middleware after execution of current Use
if a next invoker is present.
As shown, we have used next invoker with Use
extension, so that HTTP call will get transferred to next middleware even though we tried to return:
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.Use(next=> async context =>
{
await context.Response.WriteAsync("Return From Use.");
await next.Invoke(context);
});
app.Run(async context => {
await context.Response.WriteAsync("This is from Run.");
});
}
This prints both the lines
Return from Use
This is from Run
app.Map
used as a convention for branching the pipeline. Map
branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.
public class Startup
{
private static void HandleMapTest1(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Map Test 1");
});
}
private static void HandleMapTest2(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Map Test 2");
});
}
public void Configure(IApplicationBuilder app)
{
app.Map("/map1", HandleMapTest1);
app.Map("/map2", HandleMapTest2);
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from non-Map delegate. <p>");
});
}
}
The following table shows the requests and responses from http://localhost:1234
using the previous code.
Please refer to this link & link for details.
Here's the latest ASP.NET Core
documentation links - use, run , map
来源:https://stackoverflow.com/questions/35559763/owin-app-use-vs-app-run-vs-app-map