在ConfigureServices()方法中,将services.AddControllers()方法更改为services.AddControllersWithViews(),然后在Configure()方法中使用以下代码:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
使用[Route("...")]特性更改控制器和操作方法的路由。
例如:
[Route("api/[controller]")] public class ProductsController : Controller { [HttpGet("{id}")] public IActionResult Get(int id) { // ... } }
注意:在控制器上定义[Route("...")]特性时,模板引擎将不再使用控制器的名称作为默认路由。
可以使用中间件MapFallbackToFile()来指定默认页面。
例如:
app.UseEndpoints(endpoints => { endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
这段代码将map任何没有匹配的请求到index.html页面。
注意:不要将这段代码添加到路由定义之前。