c# - 是否可以在没有 AddMvc 的 ASP.Net Core 2.1 中创建路由映射?
问题描述
我对 ASP.NET Core 完全陌生,我搜索了很多,但仍然对 Core 2.1 中的路由感到困惑。
因此,我创建了一个示例项目,选择 API 作为模板,VS 创建了如下内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc();
}
但我不需要 MVC 提供的所有功能,因为我的项目不使用视图。
任何帮助将不胜感激
解决方案
Yes . Although we often use routing with MVC , Routing is a project that has no dependencies on MVC.
When working together with ASP.NET Core , Routing works as RouterMiddleware behind the scene . If you don't want to MVC , simply build a router :
private IRouter BuildRouter(IApplicationBuilder applicationBuilder)
{
var builder = new RouteBuilder(applicationBuilder);
// use middlewares to configure a route
builder.MapMiddlewareGet("/api/hello", appBuilder => {
appBuilder.Use(async (context,next) => {
context.Response.Headers["H1"] = "Hello1";
await next();
});
appBuilder.Use(async (context,next) => {
context.Response.Headers["H2"] = "Hello2";
await next();
});
appBuilder.Run(async (context) => {
await context.Response.WriteAsync("Hello,world");
});
});
builder.MapMiddlewarePost("/api/hello", appBuilder => {
// ...
});
// ....
return builder.Build();
}
And register the router middleware
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseRouter(BuildRouter(app));
}
Here's a screenshot when it works :
推荐阅读
- javascript - 无法让我的测试通过我的 freeCodeCamp 产品登陆页面课程...请帮助 :)
- ios - Xcode CarPlay 模拟器会说“CarPlay 不可用”
- c - 如何将汇编代码翻译回 C?
- html - 未聚焦且输入包含文本且不需要 HTML 时的浮动标签
- html - 使用网格时如何保持图像比例相同?
- pandas - 如何在一个轴上绘制具有一系列值的条形图以及在另一个轴上该范围内其他列的行的相应值的总和
- powershell - PreLaunchTask 找不到任务 - Powershell
- angular - 角度:带有时区信息的日期管道,如美国/埃德蒙顿
- reactjs - react-material-ui withStyle 道具为空
- scipy - 无法为通过pycall在julia中导入的scipy rbf分配自定义径向?