在Startup.cs代码中Configure()方法中写入如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endponits =>
{
endponits.MapGet("/", async (HttpContext context) =>
{
await context.Response.WriteAsync("Hello Web API app");
});
});
}
运行结果:
这里也是使用的lambda匿名方法,其中endpoints源于IEndpointRouteBuilder,等价于
IEndpointRouteBuilder.MapGet(string pattern,RequestDelegate requestDelegate)
该方法添加一个RouteEndpoint到IEndpointRouteBuilder,并对指定的pattern匹配相应的http请求
则也可以写为如下
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endponits =>
{
endponits.MapGet("/", async (HttpContext context) =>
{
await context.Response.WriteAsync("Hello Web API app");
});
endponits.MapGet("/test", async (HttpContext context) =>
{
await context.Response.WriteAsync("Hello Web API app test");
});
});
}
运行结果:
parttern: “/”
parttern: “/test”
如果配置服务中添加了控制器,则可以直接映射获取路由访问,如下代码所示:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration {
get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endponits =>
{
endponits.MapControllers();
});
}
}
也就是services.AddControllers()和 endponits.MapControllers()的相关使用。
这样就可以直接对Controllers文件夹中xxxController.cs中的路由方法进行操作了。
这种就是以AddControllers的方式注入Web API了。