user9430427
user9430427

Reputation:

mvc core2.0 routing is not Workin

Here i'm new to mvc core2.0 please help me why my Routing Is not working My Routing Class

public static class ApplicationRoteProfiler
    {
        public static void Routeing(IRouteBuilder builder)
        {
            builder.MapRoute("route1", "", new
            {
                Controllers = "Department",
                Action = "Add",

            });
            builder.MapRoute("route2", "Department/Add", new
            {
                Controllers = "Department",
                Action = "Index"

            });
        }

This class file i register in startup.config file

 public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseMvc();
            app.UseMvcWithDefaultRoute();
            app.UseMvc(routes =>
            {
                ApplicationRoteProfiler.Routeing(routes);
            });

        }

When i hit my server as http://localhost:1588/Department/Add its should redirect to Department/Index But its hitting Department/Add

Upvotes: 0

Views: 180

Answers (1)

David Liang
David Liang

Reputation: 21476

Should it be just Controller not Controllers??

builder.MapRoute("route1", "", new { controller = "department", action = "index" });

My 2 cents

  1. You shouldn't use app.UseMvcWithDefaultRoute() and app.UseMvc() at the same time. You only need to pick 1 of them.
  2. I don't see benefits of using a static class to configure routing for MVC. You can just put all the route configurations right there inside UseMvc lamba function. Also I don't think you need to put customized route specifically for your "route1" as it follows the standard MVC routing convention.

    app.UseMvc(routes =>
    {
        // The order of these routes matters!
    
        routes.MapRoute(
            name: "route2",
            template: "department/add",
            defaults: new { area = "", controller = "department", action = "index" });
    
       routes.MapRoute(
           name: "default",
           template: "{controller=home}/{action=index}/{id?}");
    }
    
  3. You can also return RedirectToAction("index"); inside your Department controller Add method so whenever /deparment/add route is hit, it redirects to /deparment/index, assuming you have the default MVC routing setup, either use the "default" route I put on #2, or use UseMvcWithDefaultRoute(). That way you don't need to create custom routes just for redirecting.

    public class DepartmentController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    
        public IActionResult Add()
        {
            return RedirectToAction("index");
        }
    }
    

Upvotes: 1

Related Questions