25 | routing and endpoint: How to plan well your Web API
Routing system in ASP.NET MVC framework which has been in existence, it has been improved in ASP.NET Core framework inside
The central role of the routing system refers to a mapping correspondence between the URL and the application of Controller
This mapping relationship actually has two effects:
1, the above URL is mapped to a corresponding action corresponding to Controller
2, according to the Controller and action names to produce URL
.NET Core offers two ways of routing registration:
1, routing template way
2, RouteAttribute way
Both methods were applied to the scene is not the same
Routing template the way before the traditional way, it can be used as a page Web MVC configuration
Now used more before and after the end of the separation of architecture, the definition of Web API when using RouteAttribute way to do it
In the middle of the process defined routing, route registration, there is an important feature is the routing constraints, is how to match routes
There are several simple constraint:
1, type constraint
2, the range of constraints
3, regular expressions
4, whether mandatory
5, custom IRouteConstraint
Further routing key system provides two classes, based on information produced for the reverse route URL address
1、LinkGenerator
2, IUrlHelper
IUrlHelper with MVC frameworks like the inside of MVCHelper
And LinkGenerator a link is provided to generate a new object, it can, at any position can be obtained from inside the container to the object, and then generates a URL address needed
Next, look at the code
Source link:
https://github.com/witskeeper/geektime/tree/master/samples/RoutingDemo
To facilitate the presentation, here to register a group Swagger code, Web API output will come out through the visual interface of Swagger
Introducing Swagger packet corresponding to ASP.NET Core
Swashbuckle.AspNetCore
The injected code documentation XML document to Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
Swagger registered in the middleware inside
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
This way you can see Swagger interface on the interface, and browse our API defined
Followed by the definition of the route OrderController
namespace RoutingDemo.Controllers
{
[Route("api/[controller]/[action]")]// RouteAttribute 的方式
[ApiController]
public class OrderController : ControllerBase
{
/// <summary>
///
/// </summary>
/// <param name="id">必须可以转为long</param>
/// <returns></returns>
[HttpGet("{id:MyRouteConstraint}")]// 这里使用了自定义的约束
public bool OrderExist(object id)
{
return true;
}
/// <summary>
///
/// </summary>
/// <param name="id">最大20</param>
/// <returns></returns>
[HttpGet("{id:max(20)}")]// 这里使用了 Max 的约束
public bool Max(long id)
{
return true;
}
/// <summary>
///
/// </summary>
/// <param name="ss">必填</param>
/// <returns></returns>
[HttpGet("{name:required}")]// 必填约束
public bool Reque(string name)
{
return true;
}
/// <summary>
///
/// </summary>
/// <param name="number">以三个数字开始</param>
/// <returns></returns>
[HttpGet("{number:regex(^\\d{{3}}$)}")]// 正则表达式约束
public bool Number(string number)
{
return true;
}
}
}
The above uses custom constraints MyRouteConstraint
namespace RoutingDemo.Constraints
{
public class MyRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (RouteDirection.IncomingRequest == routeDirection)
{
var v = values[routeKey];
if (long.TryParse(v.ToString(), out var value))
{
return true;
}
}
return false;
}
}
}
Registration MyRouteConstraint
services.AddRouting(options =>
{
options.ConstraintMap.Add("MyRouteConstraint", typeof(MyRouteConstraint));
});
Before it entered into force, need to inject UseEndpoints position in middleware registration and use of UseEndpoints MapControllers
app.UseEndpoints(endpoints =>
{
// 使用 RouteAttribute
endpoints.MapControllers();
});
By the way like this injection route incoming OrderController
Start the program, you can see a total of five interfaces
The first interface is a custom bind us to achieve, click try it out after the input parameters
The second interface constraint maximum of 20
Enter 5, execution
It can be seen that the response code is 200
Enter 25, execution
You can see the response code is 404, it said failed to match routes
The third parameter is required because the interface, there is no way to enter a null value, a verification of a front end
The fourth interfaces starts with three digits, the input 234, in line with the regular expression, response code 200
This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing.
Welcome to reprint, use, repost, but be sure to keep the article signed by Zheng Ziming (containing links: http://www.cnblogs.com/MingsonZheng/), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification .
If you have any questions, please contact me ([email protected]).