Single Url for an Controller Action method

Why there are so many ways to select an action method in ASP.NET MVC and how I avoid this? I mean, I can go to Index action method from /, /Home, /Home/Index. I think it will affect SEO ranking.

Upvotes: 0

Views: 141

Answers (2)

Quoting the answer from this site,

public class RemoveDuplicateContentAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var routes = RouteTable.Routes;
        var requestContext = filterContext.RequestContext;
        var routeData =requestContext.RouteData;
        var dataTokens = routeData.DataTokens;
        if (dataTokens["area"] == null)
            dataTokens.Add("area", "");
        var vpd = routes.GetVirtualPathForArea(requestContext, routeData.Values);
        if (vpd != null)
        {
            var virtualPath = vpd.VirtualPath.ToLower();
            var request = requestContext.HttpContext.Request;
            if (!string.Equals(virtualPath, request.Path))
            {
                filterContext.Result = new RedirectResult(virtualPath + request.Url.Query, true);
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

Upvotes: -1

Mike Mertsock
Mike Mertsock

Reputation: 12015

This is due to the default routing setup in Global.asax.cs:

routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

This configures a route with default values for both the controller and action. Thus:

  • /Home/Index will match this route with controller and action values explicitly defined
  • /Home will match the Default route and the routing config will supply a default controller of "Home"
  • / will match the Default route and the routing config will supply a default controller and action

You could change this by removing controller = "Home", action = "Index" from the third argument to MapRoute. This removes the defaults and requires that the URL explicitly specifies the controller and action.

You would want a second MapRoute call to explicitly specify a home page route:

// route the root URL to the home page controller/action
routes.MapRoute("HomePage", "", new { controller = "Home", action = "Index" });

Otherwise a request to http://yourdomain.com will not route to any controller/action pair and you would get a 404 instead of the home page.

Upvotes: 5

Related Questions