OWIN app.use vs app.run vs app.map

人盡茶涼 提交于 2019-12-03 22:49:19

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!