问题
I have enable attribute routing in route config file and I have declare attribute routing as
[RoutePrefix("receive-offer")]
public class ReceiveOfferController : Controller
{
// GET: ReceiveOffer
[Route("{destination}-{destinationId}")]
public ActionResult Index(int destinationId)
{
return View();
}
}
public class DestinationController : Controller
{
[Route("{country}/{product}-{productId}")]
public ActionResult Destination(string country, string product, int productId)
{
return View();
}
}
In above two controllers one has static prifix and other has variable prefix but I am getting Multiple controller types were found that match the URL error from these two controller.
What is wrong in this routing pattern.
回答1:
this happens when the attribute route matches multiple route you can look at this Multiple controller types were found that match the URL. so when you enter domain/receive-offer/new york-1
it matches the first Route and also the second URL because it will consider receive-offer
as a country so to resolve this we can use Route Constraints
to specify the values of routes so your route will be
[RoutePrefix("receive-offer")]
public class ReceiveOfferController : Controller
{
// GET: ReceiveOffer
[Route("{destination}-{destinationId:int}")]
public ActionResult Index(int destinationId)
{
return View();
}
}
public class DestinationController : Controller
{
[Route("{country:alpha}/{product}-{productId:int}")]
public ActionResult Destination(string country, string product, int productId)
{
return View();
}
}
since destinationId
and productId
will be of type int
and country
will be alphabet
but keep in mind that if you add spaces in country name the route will not work so you will have to apply regax
or you can remove spaces between the country name like HongKong
来源:https://stackoverflow.com/questions/43578963/multiple-controller-types-were-found-that-match-the-requested-url