【问题标题】:error in attribute routing MVC 5属性路由 MVC 5 中的错误
【发布时间】:2014-09-05 09:04:55
【问题描述】:

我正在尝试使用多个可选参数来路由操作,但它不起作用。我正在分享我的代码,请指导我。

[HandleError]
[RouteArea("Admin", AreaPrefix = "sp-admin")]
[RoutePrefix("abc-system")]
[Route("{action}")]
public class AbcController : Controller
{
   [Route("list/{id:int?}/{PersonID?}/{ref?}")]
   public async Task<ActionResult> Index(int? id, int? PersonID, string @ref)
   {
      return view();
   }
}

这不会像这样工作 http://anylocallink.com/sp-admin/abc-system/list/2/details 但像这样工作 http://anylocallink.com/sp-admin/abc-system/list/2/3/details

如果链接具有任何可选参数,我希望它能够工作。 请指导我

【问题讨论】:

  • 路由应该如何知道您在 id 和 personID 中想要“2”?这根本做不到。
  • @Shoe 有什么办法吗?

标签: asp.net asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing


【解决方案1】:

这不起作用,因为路由不知道将int 参数放在哪里。不过你可以做这样的事情

[Route("list/{type}/{id}/{ref?}")]
public async Task<ActionResult> Index(string type, int id, string @ref)
{ 
    if(type == "Person"){ ... }
    else { ... }

   return View();
}

然后你可以为一个路线做这个

list/Person/1/Details
list/ID/2/Details

【讨论】:

    【解决方案2】:

    您可以将“alpha”指定为@ref 操作参数的约束,并具有如下两个操作:

    [Route("list/{id:int?}/{ref:alpha?}")]
    public async Task<ActionResult> Index(int? id, string @ref)
    {
      return await Index(id, null, @ref);
    }
    
    [Route("list/{id:int?}/{personId:int?}/{ref:alpha?}")]
    public async Task<ActionResult> Index(int? id, int? personId, string @ref)
    {
      return View();
    }
    

    这对这两种情况都有效。我更喜欢这个,因为我不必 一次又一次地修改我的路线。

    【讨论】:

    猜你喜欢
    • 2016-11-01
    • 2013-10-28
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2014-09-07
    • 2023-04-03
    相关资源
    最近更新 更多