Rahul Khandelwal
Rahul Khandelwal

Reputation: 104

Attribute routing in MVC

Can anyone explain me about attribute routing. I am having a question about it.

When I am using "Only" attribute routing I am getting below error.

  1. When URL is "http://localhost:51254/":

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

  1. When URL is "http://localhost:51254/MyHome/HomeAction"

HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

My code in controller:

    [RoutePrefix("MyHome/{action}")]
    public class IndexController : Controller
    {
        [Route("HomeAction")]
        public ActionResult Index()
        {
            return View();
        }

        [Route("CallUs")]
        public ViewResult ContactUs()
        {
            return View();
        }
    }

And in RouteConfig.cs look like:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
        }
    }

Is there anything wrong with URL?
I tried in different way like: http://localhost:51254/Index

http://localhost:51254/Index/Index

http://localhost:51254/HomeAction

http://localhost:51254/MyHome

http://localhost:51254/MyHome/HomeAction

So if I refraim question then it will be like:
Is it mandatory to use convention based routing and objRouteCollection.mapRoute method? because if I add MapRoute method it work quite good.

I searched but couldn't find anything that answer my question. For Example msdn, c-SharpCorner

Upvotes: 0

Views: 1323

Answers (1)

Sarang
Sarang

Reputation: 83

When an action method is decorated with Route attribute , it can no longer be accessed from convention based routes defined in RouteConfig.cs

MVC expects literal string in RoutePrefix, else it will give runtime error. Actual error : "A direct route for an action method cannot use the parameter 'action'. Specify a literal path in place of this parameter to create a route to the action." So remove {action} from RoutePrefix. Now if you access 'http://localhost:xxxxx/MyHome/HomeAction', it should work.

Upvotes: 2

Related Questions