Asp.net核心默认路由

本文关键字:路由 默认 核心 net Asp | 更新日期: 2023-09-27 18:13:54

简化Startup代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute(
        name: "default",
        template: "",
        defaults: new { controller = "Main", action = "Index" });
    });
}

在Visual Studio 2015中运行应用程序后,我在浏览器中看到"localhost:xxx",但我没有看到MainController.Index()的结果。只是空白页。我错过了什么?

更新:

web . config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".'logs'stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>
更新2:

问题来自于依赖注入服务到控制器的异常,因为我忘记使用开发人员异常页面网站只是返回空白页面给我。所以我很抱歉错误的问题,但是路由在我的情况下很好。

Asp.net核心默认路由

routes.MapRoute(
    name: "default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Main", action = "Index" });
routes.MapRoute(
    name: "default",
    template: "{controller=Main}/{action=Index}/{id?}");

这是定义缺省路由的两种方式。你把它们混在一起。你总是需要定义模板。第二种方法是直接在模板中写入默认值。

对我来说最简单的方法(不使用MVC)是使用空的自定义属性[route(")]将控制器设置为默认路由,如下所示:

[ApiController]
[Route("")]
[Route("[controller]")]
public class MainController : ControllerBase
{ ... }
与<<p> em>启动。配置
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

另一个解决方案是重定向"/"到另一个url

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapGet("/", context =>
            {
                return Task.Run(() => context.Response.Redirect("/Account/Login"));
            });
        });

对于所有获得空白页的人,将PreserveCompilationContext设置为true:

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
  </PropertyGroup>

in vs2017或

"buildOptions": {   "preserveCompilationContext": true }
在project.json

在Startup.cs类中,使用方便的方法:UseMvcWithDefaultRoute():

public void Configure(IApplicationBuilder app, IHostingEnvironment 
{
   app.UseMvcWithDefaultRoute();
}

可以用来修改:


public void Configure(IApplicationBuilder app, IHostingEnvironment 
{
   app.UseMvc(routes =>
   {
      routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
   });
}

更多信息见Microsoft文档

对于任何想要提供静态默认内容(单页应用程序托管在kestrel或其他)的人来说,也有一个扩展方法MapFallbackToFile,可以像这样在Program.cs或Startup.cs中使用

app.UseEndpoints(
  endpoints =>
  {
    endpoints.MapControllers();  // not needed for this sample
    endpoints.MapFallbackToFile("index.html");
  });

app是一个IApplicationBuilder,你应该已经在你的启动代码的某个地方。