cool breeze
cool breeze

Reputation: 4811

How to get a route without the action in the URL

I want my route to look like:

/product/123

I have an action GET but I don't want that in the URL, it is currently:

/product/get/123

How to get this?

Global.asax.cs

RouteConfig.RegisterRoutes(RouteTable.Routes);

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new[] { "MyApp.Web.Controllers" }
        );    
}

Upvotes: 1

Views: 427

Answers (2)

Musab
Musab

Reputation: 1127

Add this code in routes.MapRoute before the default route.

routes.MapRoute(
    name: "Product",
    url: "Product/{id}",
    defaults: new { controller = "product", action = "get"} 

Upvotes: 1

CodingNagger
CodingNagger

Reputation: 1568

You can use the Route attribute to define your path like this:

[Route("product")]
public class ProductController {

    [Route("{productId}"]
    public ActionResult Get(int productId) {
        // your code here
    }
}

Which provides you the full route definition for "/product/{productId}" which is "/product/123" in your case. More details there: https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

Upvotes: 1

Related Questions