官术网_书友最值得收藏!

Routing to inline handlers

It is possible in ASP.NET Core to handle a request directly, that is, to not route to a controller action. We define inline handlers by using an extension method that specifies the HTTP verb and the template to match, as follows:

  • MapGet: HTTP Get
  • MapPost: HTTP Post
  • MapPut: HTTP Put
  • MapDelete: HTTP Delete
  • MapVerb: Any named HTTP verb; for example, Get is the same as using MapGet

There are actually two extension methods, MapXXX and MapXXXMiddleware, the first taking a delegate and the second a middleware class. An example follows.

These methods offer two possible signatures (except for Map<verb>, which takes the HTTP verb) and take the following parameters:

  • pattern: This is a route template.
  • requestHandler: This is a handler that takes the current context (HttpContext) and returns a task.

Here are two examples. In the first, we are merely setting the response content type and writing some text to the output:

endpoints.MapGet(
pattern: "DirectRoute",
requestDelegate: async ctx =>
{
ctx.Response.ContentType = "text/plain";
await ctx.Response.WriteAsync("Here's your response!");
});

Here, we are adding a middleware to the response:

var newAppBuilder = endpoints.CreateApplicationBuilder();
newAppBuilder.UseMiddleware<ResponseMiddleware>();

endpoints.MapGet(
pattern: "DirectMiddlewareRoute", newAppBuilder.Build());

ResponseMiddleware could be something like this:

publicclassResponseMiddleware
{
    privatereadonlyRequestDelegate _next;
 
    public ResponseMiddleware(RequestDelegate next)
    {
        this._next = next;
    }
 
    publicasyncTask InvokeAsync(HttpContext ctx)
    {
        await ctx.Response.WriteAsync("Hello, from a middleware!");
    }
}
When using MapMiddlewareXXX, you can't return the next delegate, as it is meant to be the only response.

The two approaches, using a handler or the application builder, are similar, as the former gives us direct access to the request context, while the latter allows us to add steps to the request pipeline for a particular route template. It all depends on what you want to do.

You cannot mix direct handlers with controllers: the first handler that is picked up in the routing table will be processed, and no other. So, for example, if you have MapGet followed by MapControllerRoute for the same template, the handler or action specified in MapGet will be processed, but not the controller in MapControllerRoute.

Now that we understand how to handle routing requests, next we'll learn how to constrain the applicability of a route.

主站蜘蛛池模板: 始兴县| 黄骅市| 鲁甸县| 平乐县| 沅江市| 旌德县| 乌拉特前旗| 烟台市| 南通市| 汶川县| 宁都县| 富平县| 额济纳旗| 蛟河市| 罗定市| 历史| 荣成市| 万荣县| 大厂| 新蔡县| 江达县| 阳泉市| 鱼台县| 田阳县| 墨玉县| 专栏| 津南区| 穆棱市| 缙云县| 蒲城县| 广宁县| 类乌齐县| 若尔盖县| 理塘县| 邛崃市| 濉溪县| 镇宁| 伊宁县| 广南县| 福鼎市| 靖宇县|