Multiple controller types were found that match the Requested URL

自作多情 提交于 2019-12-25 14:45:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!