简体   繁体   中英

Url not hitting MVC attribute based routing controller

I am using Attribute based routing in a MVC application. My Code is -

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

    }
}

I am trying to hit the url with variabale parameters like

/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

But it says resource not found. These all urls hit same Index action in Conventional based routing. What should I change to make it work in attribute based routing.

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 }
    );
}

The url parameters are mapped to the method's parameters, sou you need to specify them in your method's signature.

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

From here

EDIT: You can also access your query string parameters this way:

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

EDIT2: This is also a good reading

You are probably combining convention based routing with attribute routing, and you should register your areas after you map the attribute routes.

Add the area registration in Application_Start() after RouteConfig.RegisterRoutes(RouteTable.Routes)

AreaRegistration.RegisterAllAreas();

Try to use the named parameter "AreaPrefix" in RouteArea

[RouteArea("MasterData", AreaPrefix = "MasterData")]

It should work.

Also you can remove the RouteArea attribute and use only RoutePrefix in following way

[RoutePrefix("MasterData/BrandFacilityShipmentMaintenance")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM