ASP.NET MVC4 Custom routing - asp.net-mvc-4

I want to create simple blog engine. For fancy and clean url I'd like to use routing mechanism implemented in MVC4.
I added to RouteConfig.cs this lines:
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 }
);
routes.MapRoute(
name: "ArticleList",
url: "Articles/{category}/{page}",
defaults: new
{
controller = "Articles",
category = UrlParameter.Optional,
page = 1
});
}
}
And if I write in web browser url:
http://localhost:6666/Articles/SomeCategory/3
I want to move to this controller:
public class ArticlesController : ControllerBase<IHomeService>
{
public ActionResult Index(string category, int page = 0)
{
return View("~/Views/Article/Articles.cshtml");
}
}
with parameters category = "SomeCategory" and page = 1.
All I recieve is
Server Error in '/' Application.
The resource cannot be found.
What is wrong?

routes.MapRoute(
name: "ArticleList",
url: "{controller}/{category}/{page}",
defaults: new
{
category = UrlParameter.Optional,
page = 1,
action = "Index"
},
constraints: new
{
controller = "Articles"
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
EDIT
I should have added this to the answer but I was in a hurry:
Register your custom routes first, the more custom the more priority they have.
In the example above using the constraints or hard-coding the route produces the same result. Constraints are more flexible because you can use regex to restrict the controllers/actions/parameters values that your route is for. For instance, if you add a new route that uses the /category/page pattern your can then modify the controller constraint accordingly:
constraints: new
{
controller = #"^(Articles|AnotherController)$"
}

The problem is, you have an optional parameter in the middle of your {controller}/{category}/{page} path. ASP.NET routing has problem with that, because if category is not provided, it has no way to detect that the category is not provided.

To enable attribute routing, call MapMvcAttributeRoutes during configuration. Following are the code snipped.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
In MVC5, we can combine attribute routing with convention-based routing. Following are the code snipped.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
It is very easy to make a URI parameter optional by adding a question mark to the route parameter. We can also specify a default value by using the form parameter=value.

Related

Issue with default path in MVC

I am not able to set the default page in MVC. I am using lowercase-dashed-routing of git hub for url. When I open my project, I am getting 404 error. When I open page like localhost/home/index, it is working fine.
using LowercaseDashedRouting;
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
// );
routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "home", action = "Index", id = UrlParameter.Optional }),
new DashedRouteHandler() ) ); }}}

asp.net mvc4 VaryByParam does not work

My code is as below:
[HttpGet]
[OutputCache(Duration = 90, VaryByParam = "cityCode")]
public ActionResult About(string userName, string cityCode)
{
//do something...
return View();
}
the cache works fine when I access the URL:
http://localhost:52121/LabOne/MvcCache/About?userName=admin&cityCode=010
but when I access this route URL as below, the cache does not work, why?
http://localhost:52121/LabOne/MvcCache/About/admin/010
I copied your code and I tested it on my machine and I configured the RouteConfig as the following
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 }
);
routes.MapRoute(
name: "aboutRoute",
url: "{controller}/{action}/{userName}/{cityCode}",
defaults: new { controller = "Home", action = "About", userName = UrlParameter.Optional, cityCode = UrlParameter.Optional }
);
}
}
And I faced the same problem, I will explain this :
The OutputCache is depending on the URL, and the examples you provides is really two different URLs, although they are will make the same result.
So try to request the URL http://localhost:52121/LabOne/MvcCache/About/admin/010 one more time. and you will see that OutputCache is working, and the MVC will bring the result from cache, because the OutputCache has been cached this URL on previous time.
UPDATE
according to this question Using outputcache in MVC and its accepted answer, the Caching are working with the URL and has no relevance with the MVC Routing System.

Specific routing for a controller

I have this url:
http://localhost:3256/publicview/details?username=mvcpro4
which works and returns the view with data.
which i would like to be this url:
http://localhost:3256/publicview/details/mvcpro4
which doesnt work, when it gets the controller the username parameter is null.
How do i need to configure the publicview route, so it doesn't break the default routing.
I have these routes in place.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"publicview",
"publicview/details",
new { controller = "publicview", action = "details" }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
pretty much just like you have already
routes.MapRoute(
"publicview",
"publicview/details/{userName}",
new { controller = "publicview", action = "details", userName=UrlParamter.Optional }
);
Make sure that you call the string parameter userName in your details action so it populates.
or you can just remove the above route and change the parameter to id in your details action so it uses the standard route
be careful of special characters in the url, or .net runtime will kick off and throw exceptions at you.
http://blogs.iis.net/nazim/archive/2011/04/18/use-of-special-characters-like-in-an-iis-url.aspx

Make custom default page in asp.net mvc

I would like to add custom default page in Asp.net mvc so instead the page going to Home/Index , i would like to go to Account/Login. I have implement the following but it still go to Home/Index. Please advise what i did wrong. Thank you
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Custom",
url: "{controller}/{Account}/{page}",
defaults: new
{
category = UrlParameter.Optional,
page = 1,
action = "Login"
},
constraints: new
{
controller = "Account"
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Assuming the case that you want the users to be redirected to the login page or a custom page if they are not 'signed-in'.
You could create a filter attribute.
example:
[RequireHttps]
[AuthorizationFilter]
public class MyController : Controller
{
}
public class AuthorizationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//do some validation, find if the user is signed-in.
filterContext.Result = new RedirectResult(..Some where in the site..);
}
}
Change your route. The default route is set to /Home/Index
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
You can change that to be any route you wish
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "ControllerName", action = "ControllerActionName",
id = UrlParameter.Optional }
);
replace your default route (the last one) with this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);

setting custom path in routeconfig.cs in mvc 4

Below is my routeconfig.cs file in mvc4 application
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = UrlParameter.Optional }
);
routes.MapRoute(
"Outlet",
"Outlet/{bizId}",
new { controller = "Home", action = "Index" },
new { bizId = UrlParameter.Optional }
);
}
When i run the application, i need to enter /Home/Index?bizId=1 or any Id after the localhost port to run my application. It is working fine. But, now as the second route.maproute, I want the url to show as for ex: localhost:49787/Outlet?bizId=1 but this doesnt work. Please help! Thanks in advance
got the fix:
routes.MapRoute(
name: "Outlet",
url: "Outlet/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);