Check the code bellow. Here in route i want to give user enter input of username in url just like example.com/username but problem with that RouteConfig.cs is this cant take input like that. This will only take controller/method format. Please advice me how can i achieve domain/username type input form user? I want to serve that request from Test method bellow
Currently RouteConfig.cs file:
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 }
);
}
}
Test method:
public ActionResult Test(String username)
{
return View();
}
Try this.
routes.MapRoute("Id"
, "{id}"
, new { controller = "Home", action = "Test"});
Related
I have a controller called Search. A normal url would be the following:
localhost:44351/<ClientName>/Search/ByCity
This would hit my ByCity action within my SearchController.
Now however, a url such as the following example, would also need to hit an action within the SearchController:
localhost:44351/<ClientName>/Search/Pharmacy/ByCity
I need to somehow tell my SearchController, if the url contains "Pharmacy/ByCity", to go to the ByCity action.
I've tried using the routing attribute, but my app still hits my old Pharmacy action instead.
In my RouteConfig, I have this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
Then, in my SearchController, I have this:
public virtual ActionResult Pharmacy()
{
//this is an existing action, which gets hit, even when I type in "Pharmacy/ByCity", which is not what I want to happen.
}
[Route("Pharmacy/ByCity")]
public virtual ActionResult ByCity()
{
//this never gets hit
}
Any idea how to have a url containing "Pharmacy/ByCity" to hit my "ByCity" action, rather than "Pharmacy"?
Thanks
It is possible to achieve with the conventional route by set up like below:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Pharmacy",
url: "{clientname}/{controller}/Pharmacy/{action}",
defaults: new { controller = "search" }
);
routes.MapRoute(
name: "Search",
url: "{clientname}/{controller}/{action}",
defaults: new { controller = "search", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Routes are accessed depending on their Order in the routing table.
For conventional routing (RouteConfig.cs), you could add your specific route before the default route.
Remove your Route[] attributes in the controller
Use the code below for RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// add your specific route, before the default route
routes.MapRoute(
name: "SearchByCity", // random name
url: "Search/Pharmacy/ByCity",
defaults: new { controller = "Search", action = "ByCity" }
);
// this is the default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
If you want to use Attribute Route, follow steps below.
Remove the default route in RouteConfig.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
Then use the controller below, we used RoutePrefix for the controller, and Route for the actions.
[RoutePrefix("Search")]
public class SearchController : Controller
{
[Route("Pharmacy")]
public virtual ActionResult Pharmacy()
{
return View("index");
}
[Route("Pharmacy/ByCity")]
public virtual ActionResult ByCity()
{
return View("index");
}
}
I would like to ask if it's possible to model bind querystring parameter in application start up just like in controller's action method? is there any attribute class I can use to make this happen? example:
public ActionResult myMethod(MyModel modelName){
return View(modelName);
}
in MVC the application start-up defined in RouteConfig :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }
);
}
if you want to manipulate param use the id property.
I wrote a very simple web app in Flask and am porting it to ASP.NET Framework. All the functionality is in JavaScript and HTMl, so the framework should just act as scaffolding. I've got almost everything ported over, except for what seems to be a routing issue. My site expects a string token variable to be appended to the URL, like so: www.mysite.com/token-string. For development, the URL is localhost:*****/string-token, with my Index.cshtml page being displayed as default.
When I pass the URL without the token it works fine and my index page loads. However I get a 404 when I try it with the token. I'm assuming it's identifying the token as a route and is trying to navigate to it? I'm not sure how to fix it. Here are the important parts of my code:
HomeController.cs:
public class HomeController : Controller
{
public ActionResult Index(string token)
{
return View();
}
}
RouteConfig.cs:
NB: I've not changed this, not sure what to do with it.
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 }
);
}
}
It's quite important that the token is passed in the way it is, rather than as a ? query parameter or anything like that. Additionally, the C# index view doesn't really need to do anything with the token - it gets extracted by the JavaScript.
Any advice is most welcome. Thanks.
Each segment (i.e. {controller}) in the route is a variable, and in the default route makes them all optional. Therefore, your default route is matching the request www.mysite.com/token-string.
What you need to do is insert a route that has a constraint to only match URLs with your token. Assuming your token is a GUID, you could use a regex route constraint as follows:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "TokenRoute",
url: "{token}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { token = #"^[0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12}$" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
If your token is not a GUID, you could either use a different regex or implement IRouteConstraint to ensure the route only matches your tokens. The logic you use could be as simple as a == statement (as shown) or more complex (such as a database lookup).
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "TokenRoute",
url: "{token}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { token = new TokenConstraint() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
public class TokenConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if ((string)values[parameterName] == "MyToken")
{
return true;
}
return false;
}
}
Note that you should use the route value key {token} in the url: parameter to match the action method parameter name token.
public ActionResult Index(string token)
{
return View();
}
I guess you could try changing the default route to include token instead of id as shown below.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{token}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The default Route pattern which you have expects the parameter with name as 'id'
Either add (or modify the default route) like below route pattern
routes.MapRoute(
name: "AnotherRoute", //your desired route name
url: "{controller}/{action}/{token-string}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Greetings New to MVC ...
I am creating my first MVC Application, and I have created it as follows:
CustomUtilities/Controllers/GCItemRetrievalController.cs
CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
CustomUtilities/Views/Web.config
I want to pull up "GCRetrieve.cshtml in my browser ... but I keep getting a 404 Error
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
what am I doing wrong? I created the folders for the controllers, models, and Views in a seperate folder on the main system.
Your controller should look something like this:
public class GCItemRetrievalController : Controller
{
public ActionResult GCRetrieve()
{
return View();
}
}
When you navigate to the following url:
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
It should find the controller's GCRetrieve method and execute it. The return View() call will look for a .cshtml file named GCRetrieve.cshtml, as that is the name of the method.
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 }
);
}
}
When you create a MVC application a class file named as RouteConfig.cs is created in App_Start directory. It has default routing as
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 }
);
}
}
In the above default routing:
if you want call a view CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
I think CustomUtilities is your project name then use following
http://mainsite/GCItemRetrieval/GCRetrieve
that is
[domanin]/[controllername]/[actionname]
For default routing detail you can refer to http://www.niceonecode.com/Q-A/DotNet/MVC/routing-in-mvc-4/20190
I want to create a URLs shortener website. URLs that I offer are like example.com/XXX where
XXX is the value of the short URL.
I want to have website on example.com and URLs are example.com/xxx. I want to get xxx from URL and redirect users to equivalent URLs in database.
How can implement this?
Create a new route in your RouteConfig for example:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("empty",
"{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
And the simply go to your database with the id passed in the index
public ActionResult Index(int id)
{
//Do Stuff with db
return View();
}
asp.net mvc documentation here.
One way you be doing the needed redirection in the default controller action. By default in asp.net mvc it is home/index.
So in the index action you should be having such code
public ActionResult Index(string id)
{
var url = Db.GetNeededUrl(id);
return Redirect(url);
}
So now if the user enters such an address site.com/NewYear you'll get redirected to the equivalent url that is in you database.