1. 路由注册方式
- 路由模板的方式(MVC页面的Web配置)
- RouteAttribute方式(更适合WebApi)
2. 路由约束
- 类型约束
- 范围约束
- 正则表达式
- 是否必选
- 自定义IRouteConstraint
3. URL生成
4. 注册Swagger并将xml文件注入
如果没有xmlwen文件:项目->鼠标右键->属性->生成->输出->XML文档文件(勾选)
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "NET_Core", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "NET_Core v1"));
5. 路由约束代码
备注1:[Route("api/[controller]/[action]")],action会将相应的方法名作为url
备注2:约束校验不通过,是不会走向接口里面的
[Route("api/[controller]/[action]")]
[ApiController]
public class OrderController : ControllerBase
{
/// <summary>
/// 自定义约束
/// </summary>
/// <param name="id">必须可以转long</param>
/// <returns></returns>
[HttpGet("{id:isLong}")]
public bool OrderExist([FromRoute]string id)
{
return true;
}
/// <summary>
/// 最大值
/// </summary>
/// <param name="id"></param>
/// <param name="link"></param>
/// <returns></returns>
[HttpGet("{id:max(20)}")]
public bool Max(long id,[FromServices]LinkGenerator link)
{
var a = link.GetPathByAction("Reque", "order");
return true;
}
/// <summary>
/// 必填
/// </summary>
/// <param name="name">姓名</param>
/// <returns></returns>
[HttpGet("{name:required}")]
public bool Reque(string name)
{
return true;
}
/// <summary>
/// 正则表达式
/// </summary>
/// <param name="number">以3个数字开始</param>
/// <returns></returns>
[HttpGet("{number:regex(^\\d{{3}}$)}")]
public bool Number(string number)
{
return true;
}
}
public class MyRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if(RouteDirection.IncomingRequest == routeDirection)
{
var val = values[routeKey];
if(long.TryParse(val.ToString(),out var value) == true)
{
return true;
}
}
return false;
}
}
注册自定义路由约束:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDirectoryBrowser();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "NET_Core", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
//添加自定义路由验证
services.AddRouting(options =>
{
options.ConstraintMap.Add("isLong", typeof(MyRouteConstraint));
});
}
6. 链接生成
/// <summary>
/// 最大值
/// </summary>
/// <param name="id"></param>
/// <param name="link"></param>
/// <returns></returns>
[HttpGet("{id:max(20)}")]
public bool MaxUrl(long id, [FromServices] LinkGenerator link)
{
//相对地址
var a = link.GetPathByAction(HttpContext,
action: "Reque",
controller: "Order",
values: new { name = "abc" });
//绝对地址
var uri = link.GetUriByAction(HttpContext,
action: "Reque",
controller: "Order",
values: new { name = "abc" });
return true;
}
7. 接口废弃
方法名上加上:?[Obsolete]
|