MVC route with single level - asp.net-mvc-4

I need to build a controller action to handle this pattern:
example.com/aString
where aString can be any of a set of arbitrary strings. The controller would cycle thru each of the possible values and, if none match, redirect to a 404.
I'd think it's just a matter of recoding the catch-all but am so far coming up blank. Currently using Sherviniv's suggestion:
//Catchall affiliate shortcuts.
routes.MapRoute(
name: "affLanding",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
Controller:
public ActionResult MatchString(string query)
{
_logger.Info("affLanding: " + query);
return View();
}
If i hard-code my 'search' string into the route.config things work:
routes.MapRoute(
name: "search",
url: "aString",
defaults: new { controller = "home", action = "MatchString"}
);

In routeconfig
routes.MapRoute(
name: "Controller1",
url: "Controller1/{action}/{id}",
defaults: new { controller = "Controller1", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Controller2",
url: "Controller2/{action}/{id}",
defaults: new { controller = "Controller2", action = "Index", id = UrlParameter.Optional }
);
//Other controllers
routes.MapRoute(
name: "search",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
routes.MapRoute(
name: "Default",
url: "",
defaults: new
{
controller = "Home",
action = "Index"
}
);
In your Controller
public ActionResult Index()
{
reutrn view();
}
public ActionResult MatchString(string query)
{
if(Your Condition)
{
//when string query doesnt find
throw new HttpException(404, "Some description");
}
else
{
return view(Your model);
}
}
Remember to add all of your controller's name because if you don't mention them in route config how the server can know it is search parameter or Not.
Hope it helps

Related

Routing in MVC is not working

I am reading an ebook on MVC.
It have following examples but none of them are working.
routes.MapRoute("", "X{controller}/{action}");
routes.MapRoute("", "Public/{controller}/{action}",
new { controller = "Home", action = "Index" });
Both of them will go to Home controller and index action
Link for First route: http://localhost:14099/XHome/Index
Link for Second route: http://localhost:14099/Public/Home/Index
The output of the both should be the same as per the example in the book. But when i'm trying the same it is not giving any result. i.e resource cannot be found. Am i doing anything wrong here?
Following is my code which i have written:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute("", "X{controller}/{action}");
routes.MapRoute("MyRoute", "{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("", "Public/{controller}/{action}",
new { controller = "Home", action = "Index" });
}
I was writing the routes after default which is wrong, so i had to write it before the default which is quite obvious.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("", "X{controller}/{action}");
routes.MapRoute("MyRoute", "{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("", "Public/{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

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 }
);

MapRoute with my extension

How to create right MapRoute with my extension? (e.x. "my").
This MapRoute is correct
routes.MapRoute(
name: "Default",
url: "{controller}.my/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
But I want use controller.my?id.
This MapRoute is wrong
routes.MapRoute(
name: "",
url: "{controller}.my/{tid}",
defaults: new { controller = "Home", action = "Index", tid = UrlParameter.Optional }
);
I think that if you add parameters in MapRoute, you can't simply use them as query strings.
Remove those parameters which you want to use them as query strings from MapRoute, and simply use them in action methods:
routes.MapRoute(
name: "",
url: "{controller}.my",
defaults: new { controller = "Home", action = "Index" }
);
Action method:
public ActionResult Index(string tid) // or int tid ...
{
// ...
}
So you can access that by something like ~/Home.my?tid=someThing

MVC4 Default route when using areas

I'm trying to use areas within MVC app, I would like that the default route will be resolved to the HomeController within the admin area but it resolves to the home controller in root site.
I added the namespace of the admin HomeController but it still resolved to the root HomeController.
My Route config:
public class RouteConfig
{
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[] {"MvcApplicationAreas.Areas.Admin.Controllers"}
);
}
}
admin area route
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
HomeController - Admin area
namespace MvcApplicationAreas.Areas.Admin.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Any idea why it wouldn't resolve properly?
Thanks
The most straightforward way is to add a data token to your default route:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional }
).DataTokens.Add("area", "Admin");
Simply add
.DataTokens.Add("area", "[your area name]");
to the end of your default route definition.
I've tested your code for the area registration and it works and selects the right controller. However, the view resolution finds the view in the root folder, even if the right controller is used.
To test, I used the following home index action in my areas home controller:
public ActionResult Index()
{
return View(model: "Admin area home controller");
}
Then my index.chstml in /Views/Home:
Root View: #Model
and my index.cshtml in /Areas/Admin/Views/Home:
Admin Area view: #Model
When run, the output is:
Root View: Admin area home controller
So the route makes the home controller in the admin area run, but then thew view resolution goes on and finds the root view instead of the admin view.
So in the end, it is indeed the view selection that is wrong, so your problem is the same as in How to set a Default Route (To an Area) in MVC.
This solution will broke your API route.
You must have some unique name for each area, like the default area makes it:
context.MapRoute(
"Common_default",
"**Common**/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
The correct solution to default route below:
Web area route:
context.MapRoute(
"Common_default",
"Common/{culture}/{controller}/{action}/{id}",
new {culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Main route which redirect users to the "Common" area:
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "SMS.Sender.Areas.Common.Controllers" }
).DataTokens.Add("area","Common");
Try doing this way....it will help in distinguish.Even if you dont add area="Web", its fine
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", area="Web", id = UrlParameter.Optional },
new[] { "Nop.Web.Controllers" }
).DataTokens["UseNamespaceFallback"] = false;
Same way
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", area = "Admin", id = "" },
new[] { "Nop.Admin.Controllers" }
);
Add the Index action method in your default root home controller. In the Index action method use "return redirecttoaction" statement for the default area redirection
public ActionResult Index()
{
return RedirectToAction("Dashboard", "Home", new {area = "Home"});
}
Default route should be
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home",
action = "Index", id = UrlParameter.Optional}
);
Easiest way to route from areas from AreaRegistration Page:
context.MapRoute("MainDefault", "Main/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } , new[] { "Namespace.To.Controllers" });
context.MapRoute("ClearPath", "", new { controller = "Home", action = "Index" }, new[] { "Namespace.To.Controllers" });
In your
RouteConfig.cs
routes.MapRoute("redirect all other requests", "{*url}",
new {
controller = "UnderConstruction",
action = "Index"
}).DataTokens = new RouteValueDictionary(new { area = "Shop" });
default route is by default route in MVC will call at first because in MVC which route is specified very first it will call like that

ASP.NET MVC 4 Routes not working

Route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Contact",
url: "Contact",
defaults: new { controller = "Home", action = "Contact" }
);
my controller
public class HomeController : BaseController
{
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
My Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
Finally my request url
http://localhost:1234/Contact/
Error on browser
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
Requested URL: /Contact/
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.18033
What am I doing wrong?
Solution:
Custom route should take the precedence
routes.MapRoute(
name: "Contact",
url: "Contact",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The Framework always tries to match the URL of the request to a route in the order of the Routes added to the RouteCollection
So you should put the custom routes before the default route,
//Custom route
routes.MapRoute(
name: "Contact",
url: "Contact",
defaults: new { controller = "Home", action = "Contact" }
);
//default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
You can use:
routes.MapRoute(
name: "Default",
url: "{*p}",
defaults: new { controller = "Home", action = "Index", p = UrlParameter.Optional }
);
The asterisk indicates that it's a catch-all route. Keep in mind that these routes are extremely greedy, make sure that this stays below any specific routes.
You could also add a route constraint to this route which can determine whether the page exists in the database or something.