Search code examples
c#routesasp.net-core-mvc

Unable to specify route in ASP.NET MVC


I am new to ASP.NET MVC. I am using visual studio to setup a small project. But there is no app_start folder so I can make changes to routeconfig file. There is a program.cs file where it contained the routecontroller, but there is no effect on it. The default method still remains Index.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
    name: "Read",
    pattern: "{controller=Read}/{action=Welcome}/{id?}");

So I created a folder with routeconfig file, but it doesn't recognizes the ignore route method and unable to run it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SecondProject
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Kindly help.


Solution

  • This doesn't fit to a comment. Therefore, I put it as an answer.

    Your question contains parts of code related to different versions of the ASP.NET. The first related to the ASP.NET Core MVC and the second for ASP.NET Framework MVC. These are different version with different routing implementation. You should use the correct template when you build your project - this depend on your requirements.

    The question is: Which version you are using?

    If your project doesn't contain app_start folder, but contains program.cs file this means that you are using ASP.NET Core MVC. Then look at the documentation hot to implement routing in your application: Routing to controller actions in ASP.NET Core


    To make the Welcome action method as the default remove the first route template declaration and leave only the "Read" pattern:

    app.MapControllerRoute(
        name: "Read",
        pattern: "{controller=Read}/{action=Welcome}/{id?}");