【问题标题】:Simple ASP.NET Core routing issue简单的 ASP.NET Core 路由问题
【发布时间】:2018-06-13 17:47:52
【问题描述】:

使用以下

app.UseMvc(routes =>
{
    routes.MapRoute(
       name: "beacon",
       template: "beacon/{id?}");

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

http://www.example.com/beacon 符合我的预期并点击了BeaconController

http://www.example.com/beacon/001 没有击中任何控制器并进入 404

我错过了什么?

【问题讨论】:

  • BeaconController 中是否有一个Index 操作方法,可以接受整数类型的输入id 参数?

标签: c# asp.net-core asp.net-core-routing


【解决方案1】:

您指定了路由模式 URL,但未提及应由哪个控制器/操作处理这些类型的请求。

您可以在定义路由时指定默认选项

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "beacon",
      template: "beacon/{id?}", 
      defaults: new { controller = "Beacon", action = "Index" }
    );

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

假设您的 Index 方法有一个可空 int 类型的 id 参数

public class BeaconController : Controller
{
    public ActionResult Index(int? id)
    {
        if(id!=null)
        {
            return Content(id.Value.ToString());
        }
        return Content("Id missing");    
    }
}

另一种选择是从UseMvc 方法中删除特定的路由定义,并使用属性路由指定它。

public class BeaconController : Controller
{
    [Route("Beacon/{id?}")]
    public ActionResult Index(int? id)
    {
        if(id!=null)
        {
            return Content(id.Value.ToString());
        }
        return Content("Id missing");
    }
}

http://www.example.com/beacon 工作的原因是因为该请求结构与为默认路由定义的模式匹配。

【讨论】:

  • 是 - 在默认值中指定控制器的名称。仅命名路由并不能将其连接到正确的控制器。我正在学习 - 谢谢 Shyju!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 2018-08-11
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多