Url 没有命中基于 MVC 属性的路由控制器

Url not hitting MVC attribute based routing controller

我在 MVC 应用程序中使用基于属性的路由。我的代码是 -

[RouteArea("MasterData")]
[RoutePrefix("BrandFacilityShipmentMaintenance")]
public class BrandFacilityShipmentMaintenanceController : Controller
{
    [Route("Index")]
    public ActionResult Index()
    {

    }
}

我正在尝试使用

等可变参数来达到 url
/MasterData/BrandFacilityShipmentMaintenance/Index
/MasterData/BrandFacilityShipmentMaintenance/Index/1156?pid=1120
/MasterData/BrandFacilityShipmentMaintenance/Index/1156?pid=1120&fname=Brand+Facility+Shipment+Maintenanca
/MasterData/BrandFacilityShipmentMaintenance/Index/1156?pid=1120&fname=Brand+Facility+Shipment+Maintenanca&isReffered=false

但是提示找不到资源。这些所有 url 在基于传统的路由中都命中了相同的索引操作。我应该更改什么才能使其在基于属性的路由中工作。

AreaRegistration.cs -

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.Routes.MapMvcAttributeRoutes();
    context.MapRoute(
        "Masterdata_default",
        "Masterdata/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

您可能将基于约定的路由与属性路由相结合,您应该在映射属性路由后注册您的区域。

RouteConfig.RegisterRoutes(RouteTable.Routes)

之后添加Application_Start()中的区域注册
AreaRegistration.RegisterAllAreas();

尝试在RouteArea

中使用命名参数"AreaPrefix"
[RouteArea("MasterData", AreaPrefix = "MasterData")]

应该可以。

也可以去掉RouteArea属性,只使用RoutePrefix,方法如下

[RoutePrefix("MasterData/BrandFacilityShipmentMaintenance")]

url 参数映射到方法的参数,因此您需要在方法的签名中指定它们。

public string Index(int id, int? pid)  { ... }

来自here

编辑: 您还可以通过这种方式访问​​您的查询字符串参数:

public ActionResult Index(int id)
{ 
    string param1 = this.Request.QueryString["pid"];
    // parse int or whatever
}

EDIT2:This 也是一本好书