I have this in my RouteConfig:
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: "StoreSearch",
url: "{storeName}",
defaults: new { controller = "Search", action = "Store" }
);
Basically I have a 2nd route so if I type in localhost:9000/facebook there is no such controller by the name of facebook so my 2nd router should pickup facebook as the storeName and hit my Search controller's Store action. But at the moment I get 404.
Any ideas how do I fix this?
If you have specific set of stores or a way to verify them you can add a constraint to the route.
To add a generic constraint with match predicate
public class ServerRouteConstraint : IRouteConstraint
{
private readonly Func<Uri, bool> _predicate;
public ServerRouteConstraint(Func<Uri, bool> predicate)
{
this._predicate = predicate;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return this._predicate(httpContext.Request.Url);
}
}
and then in the route add a paramater
routes.MapRoute(
name: "StoreSearch",
url: "{storeName}",
defaults: new { controller = "Search", action = "Store" }, constraints:
//this could be new { controller ="pattern" }
new {
serverRoute = new ServerRouteConstraint(url =>
{
//this will check that the route starts with a specific string in this case Settings
return url.PathAndQuery.StartsWith("/Settings",
StringComparison.InvariantCultureIgnoreCase);
})
});
For examples check: https://www.c-sharpcorner.com/UploadFile/dacca2/route-constraints-in-mvc/
Also, routes should be added from most specific to most general.
You should place any custom route above the Default route.
Just swap the order and you good to go
//before default route
routes.MapRoute(
name: "StoreSearch",
url: "{storeName}",
defaults: new { controller = "Search", action = "Store" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Related
Upon login I want to re route to a new page. (Example: mysite.com/Dashboard/User/Username)
I also want it to verify that user is logged in before it allows access to said URL.
I'm new to MVC and C# and appreciate your help.
My controller: What do I pass into the controller to make it work?
public class DashboardController : Controller
{
// GET: Dashboard
public ActionResult User()
{
return View();
}
}
Route.config.cs:
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: "UserNameRoute",
url: "{username}",
defaults: new { controller = "Dashboard", action = "User", username = "" }
);
}
}
I believe it should be something like this:
routes.MapRoute(
name: "UserNameRoute",
url: "Dashboard/User/{username}",
defaults: new { username = "" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I chose not to put the {controller} and {action} placeholders in the template as that would make it equal to the default route template. You could of course use just the action template if that is what you need:
routes.MapRoute(
name: "UserNameRoute",
url: "Dashboard/{action}/{username}",
defaults: new { action = "User", username = "" }
);
Also note I put it before the default route because it is more specific. Otherwise the default route would catch every request.
Authorization is something you can't do here however. You will need to do that by e.g. creating a custom AuthorizeAttribute subclass that checks the username matches the logged in user.
I have page, which content and URL changes from database. However, I want to set URL like
localhost:xxxx/MyPage
Now I got
localhost:xxxx/Pages/MyPage
which I don't need. What can I do for change it?
My route
routes.MapRoute(
name: "LandingPage",
url: "Pages/{*urltitle}",
defaults: new { controller = "Admin", action = "LandPage", urltitle = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
My code for change content and URL
public ActionResult LandPage()
{
string temp = RouteData.Values["urltitle"].ToString();
var item = RepositoryManager.Instanse.LandingContentRepository.GetItemByURL(temp);
IEnumerable<LandingContent> list = new List<LandingContent>() { item };
ViewBag.HtmlStr = item.HTMLText;
return View(ViewBag);
}
Well, I kinda solved it
my final route
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "LandPage",
url: "{segment}",
defaults: new { controller = "Home", action = "LandingPage" }
And in HomeController you do this
[AllowAnonymous]
public ActionResult LandingPage(string segment)
{some logic}
I have the following action
public ActionResult TemplateBuilder(int id, int? processId) { }
And then I have the following
#Url.Action("TemplateBuilder","InspectionTemplate")/id/processId
The url then looks like: InspectionTemplate/TemplateBuilder/1/2
But if I use
return RedirectToAction("TemplateBuilder","InspectionTemplate", new { id=1, processId = 2});
Then I get the following result: InspectionTemplate/TemplateBuilder/1?processId=2
How can I fix that.
Here is my Routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "IDRoute",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Login",
action = "Index",
id = UrlParameter.Optional
}
);
routes.MapRoute(
name: "ProcessRoute",
url: "{controller}/{action}/{id}/{processId}",
defaults: new
{
controller = "InspectionTemplate",
action = "TemplateBuilder",
id = UrlParameter.Optional,
processId = UrlParameter.Optional
}
);
routes.MapRoute(
name: "DateRoute",
url: "{controller}/{action}/{year}/{month}/{day}",
defaults: new
{
controller = "Inspection",
action = "Assign",
year = UrlParameter.Optional,
month = UrlParameter.Optional,
day = UrlParameter.Optional
}
);
}
You have 3 issues with your route definitions
Only the last parameter in a route definition can be marked with
UrlParameter.Optional. If you were to provide only one, then the
routing engine has no way of knowing which parameter should be bound
so the value(s) would be added as query string parameters).
The main issue however is the order of the routes. The routing
engines searches the definitions in the order they are declared and
stops as soon as it finds a matching one, and in your case the
IDRoute will match so the routes need to be swapped.
That alone however may cause issues with other route definitions, so
its best to make your route uniquely identifiable, for example by
specifying the controller name in the route definition.
Your definitions should be
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "ProcessRoute",
url: "InspectionTemplate/{action}/{id}/{processId}",
defaults: new { controller = "InspectionTemplate", action = "TemplateBuilder", processId = UrlParameter.Optional }
);
routes.MapRoute(
name: "DateRoute",
url: "Inspection/{action}/{year}/{month}/{day}",
defaults: new { controller = "Inspection", action = "Assign", } // assumes all parameters are required
);
// The default will only be match if the url does not start with '/InspectionTemplate/' or '/Inspection/'
routes.MapRoute(
name: "IDRoute",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);
}
Struggling to work out how to have the following
http://localhost/star/regulus
the only way it will work is to have a web address of
http://localhost/star/index/regulus
This is my 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( "", "star/{sstar}", new { Controller = "star", id = UrlParameter.Optional });
and in the Controller, I set up the View as :-
return View("~/views/star.cshtml", oStar);
so you can see I'm not using Index.cshtml
Any ideas how I get the top web address, not the second one.
You need to rearrange your routes
routes.MapRoute(
name: "StarRoute",
url: "star/{sstar}",
defaults: new { controller = "Star", action = "Star", sstar = UrlParameter.Optional}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The default controller should usually be the last route registered
Assuming controller
public class StarController :Controller {
public ActionResult Star(string sstar){
//...other code that uses sstar parameter
return View();
}
}
The view should be located at...
~/Views/Star/Star.cshtml
...for the following URIs to work:
http://localhost/star/regulus
http://localhost/star?sstar=regulus
http://localhost/star/sirius
http://localhost/star?sstar=sirius
Im trying to make a custom router for my mvc-learning project.
I want to keep the standrard route that directs to {controller}/{action}/{id} in case of a URL like
domain.com/user/details/72
but if i get a url like this one
domain.com/2
i want to route to a specifik controller action that takes the number as an id. So i dont want the URL to specify controller and action, cause i want the url to be real short and the controller and action should always be the same.
Ive kind of made it work but i get very strange unpredictable results so i wanted to ask if im doing something very weird. Here are my routes:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DisplayKombak",
url: "{kombakId}",
defaults: new { controller = "Kombak", action = "DisplayKombak", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Try something like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DisplayKombak",
url: "{kombakId}",
defaults: new {controller = "Kombak", action = "DisplayKombak"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
}
And KombakController.cs:
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class KombakController : Controller
{
public ActionResult DisplayKombak(string kombakId)
{
return View();
}
}
}
You may be able to force this behavior by adding route constraints.
routes.MapRoute(
name: "DisplayKombak",
url: "{kombakId}",
defaults: new { controller = "Kombak", action = "DisplayKombak", id = UrlParameter.Optional },
new {kombakId = #"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new {controller = #"\D+" }
);
The constraint on the first route will prevent the route from matching unless the first route segment is an integer, the constraint on the second route will prevent the route from matching if the first route segment is not a string of letters.