2

I try to use attribute based routing. But when i try the following snippet to activate attribute based routing i get the following error message:

RouteCollection' doesn't contain a definition for 'MapMvcAttributeRoutes

This is my code:

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

}

These are the references:

using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;

Thre Framework version for my project is 4.5.2.

Whats wrong here and how i fix this?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
STORM
  • 4,005
  • 11
  • 49
  • 98
  • What version of mvc are you using? see here http://stackoverflow.com/questions/37991768/routecollection-doesnt-contain-a-definition-for-mapmvcattributeroutes – Ric Aug 09 '16 at 12:14
  • Its 4.0.0.1/Runtimeversion v4.0.30319. When i create a new project i select > create an empty ASP.NET 4.5.2 project within Visual Studio. – STORM 1 min ago edit – STORM Aug 09 '16 at 13:30
  • 1
    `routes.MapMvcAttributeRoutes()` is only available from MVC5+ – Ric Aug 09 '16 at 13:31
  • Can i create under Visual Studio an empty ASP.NET 4.5.2 project and add MVC5 to it? – STORM Aug 09 '16 at 13:34

1 Answers1

2

I got it work now. I did the following:

I added first a new folder called App_Start. Within this folder i created a new class file named RouteConfig.cs.

The following code was added to the file above:

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

The i added a global.asax file to my project with the following code in Application_Start method:

    protected void Application_Start(object sender, EventArgs e)
    {
        //AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

Then under Extras > NuGet Package Manager > Pacakge Manager Console i added the Microsoft ASP.NET MVC 5.2.3 package to my project.

Finally i added a new MVC5 Empty controller with following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication4.Controllers
{
    [RoutePrefix("products")]
    public class DefaultController : Controller
    {
        // GET: Default
        [Route]
        public ActionResult Index()
        {
            return Content("It Works!");

            //return View();
        }
    }
}

After this i was able to open my project in the project by typing:

http://localhost:65311/products
STORM
  • 4,005
  • 11
  • 49
  • 98