文章目录
一、添加Swagger包
1.ConfigureServices中注入
代码如下(示例):
services.AddSwaggerGen(gen => {
gen.SwaggerDoc("v1.0", new Microsoft.OpenApi.Models.OpenApiInfo() { Title="My Api",Version="1.1"});
string file = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
string path = Path.Combine(AppContext.BaseDirectory, file);
gen.IncludeXmlComments(path);
});
2.Configure中配置Swagger
代码如下(示例):
app.UseSwagger();
app.UseSwaggerUI(optons => {
optons.SwaggerEndpoint("/swagger/v1.0/swagger.json","My Api 1.0");
});
3.输出Xml文档
在项目属性->生成中选择
如果不选XML文档文件,IncludeXmlComments就找不到路径,Swagger的文档就无法生成。
二、路由注册方式
1.路由模板的方式
代码如下(示例):
[HttpGet("{name:required}")]
[Obsolete]
public bool Require(string name)
{
return true;
}
2.RouteAttribute 方式
- 实现IRouteConstraint接口
代码如下(示例):
public class CustomRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
var value = values[routeKey];
return long.TryParse(value.ToString(), out long v);
}
return false;
}
}
- 在ConfigureService中添加路由规则映射
代码如下(示例):
services.AddRouting(routeOpt => {
routeOpt.ConstraintMap.Add("IsLong", typeof(CustomRouteConstraint));
});
3.Api调用
代码如下(示例):
[HttpGet("{id:IsLong}")]
public bool ExistClient(string id)
{
return true;
}
三、路由约束
1.是否必选
代码如下(示例):
[HttpGet("{name:required}")]
[Obsolete]
public bool Require(string name)
{
return true;
}
2.正则表达式
代码如下(示例):
[HttpGet("{number:regex(^\\d{{3}}$)}")]
public bool ChkIsNumber(string number)
{
return true;
}
3.范围约束
代码如下(示例):
[HttpGet("{id:max(20)}")]
public bool Max([FromRoute] long id, [FromServices] LinkGenerator linkGenerator)
{
string path = linkGenerator.GetPathByAction(HttpContext, action: "Require", controller: "Client"
, values: new { name = "fisea" }
);
string url = linkGenerator.GetUriByAction(httpContext: HttpContext, action: "Require", controller: "Client",
values: new { name = "fisea" });
return true;
}
4.自定义 IRouteConstraint
代码如下(示例):
[HttpGet("{id:IsLong}")]
public bool ExistClient(string id)
{
return true;
}
四、URL 生成
1.LinkGenerator来生成url
代码如下(示例):
string url = linkGenerator.GetUriByAction(httpContext: HttpContext, action: "Require", controller: "Client",
values: new { name = "fisea" });
2.LinkGenerator来生成path
代码如下(示例):
string path = linkGenerator.GetPathByAction(HttpContext, action: "Require", controller: "Client"
, values: new { name = "fisea" }
);