I just created below action in my controller:
public ActionResult Serial(string letterCase)
{
string serial = "SAM_ATM_1.0.0";
if (letterCase == "lower")
{
return Content(serial.ToLower());
}
return Content(serial);
}
and added below routing rules above default action:
routes.MapRoute(
name: "Serial",
url: "serial/{letterCase}",
defaults: new { controller = "Home", action = "Serial", letterCase = "upper" }
);
However calling url http://localhost:5532/home/serial/lower in debug session, letterCase is passed with null value.
Because you call localhost:5532/home/serial/lower, try to call localhost:5532/serial/lower
or, if you need localhost:5532/home/serial/lower, rewrite your route rule to
routes.MapRoute(
name: "Serial",
url: "home/serial/{letterCase}",
defaults: new { controller = "Home", action = "Serial", letterCase = "upper" }
);
Related
I currently have the following url implemented:
https://example.com/controller/challenge/{params}
and would like to create a second url that accepts a different set of parameters: https://example.com/controller/v2/challenge/{params}.
I cannot seem to get the "v2" to be hardcoded into the url path. Rather, the only way I can make it work at the moment is using https://example.com/controller/challengev2/{params}
In my configuration file:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "controller", action = "Challenge", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ChallengeV2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "controller", action = "Challengev2", id = UrlParameter.Optional }
);
My controller is set up like:
public async Task<ActionResult> Challenge(string resumePath, string refid, string client_id)
{
}
[ActionName("Challengev2)]
public async Task<ActionResult> Challenge(string refid)
{
}
I have tried modifying the url when defining the route to:
routes.MapRoute(
name: "ChallengeV2",
url: "controller/v2/Challenge/{id}",
defaults: new { controller = "controller", action = "Challengev2", id = UrlParameter.Optional }
);
But this seems to throw a 404 error. Is there a step that I am missing to create that endpoint?
Switch the order you define your routes. The order plays an extremely important role.
routes.MapRoute(
name: "ChallengeV2",
url: "controller/v2/Challenge/{id}",
defaults: new { controller = "controller", action = "Challengev2" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "controller", action = "Challenge", id = UrlParameter.Optional }
);
To create a v2 route prefix, I would recommend you to use route attribute instead of route map.
Using route attribute, your code would be like this:
public class ChallengeController
{
[Route("/challenge/{resumePath}/{refid}/{client_id}")]
public async Task<ActionResult> Challenge(string resumePath, string refid, string client_id)
{
// ...
}
[Route("/v2/challenge/{refid}")]
public async Task<ActionResult> Challenge(string refid)
{
// ...
}
}
I have the following action:
public ActionResult CatchAll(string pathname, bool isPreview)
{
CatchAllModel model = _aliasModelBuilder.BuildCatchAllModel(pathname, isPreview);
if (model.Page != null)
{
return View(model);
}
else
{
throw new HttpException(404, "Page not found");
}
}
And the route for this is
routes.MapRoute(
name: "Default",
url: "{*pathname}",
defaults: new { controller = "Alias", action = "CatchAll", isPreview = false });
Now if I browse to localhost/about-us?isPreview=true, the pathname comes through as about-us but isPreview comes through as false.
Is there anything I'm doing wrong - I thought the route default should be overwritten by the query string
Ok this looks as if the default parameter set in the route is not being overwritten by the querystring. So I removed it from the route:
routes.MapRoute(
name: "Default",
url: "{*pathname}",
defaults: new { controller = "Alias", action = "CatchAll" });
And added it to the action:
public ActionResult CatchAll(string pathname, bool isPreview = false)
I guess I'll have to suppress CA1026 as we can't make overload methods for actions
I've declared Index action in Home controller:
[HttpGet]
public ActionResult Index(string type)
{
if (string.IsNullOrEmpty(type))
{
return RedirectToAction("Index", new { type = "promotion" });
}
return View();
}
That accepts:
https://localhost:44300/home/index?type=promotion
and
https://localhost:44300/?type=promotion
Everything was ok until I config route for 404 page:
routes.MapRoute(
name: "homepage",
url: "home/index",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "default",
url: "/",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "Error", action = "PageNotFound" }
);
Invalid syntax:
The route URL cannot start with a '/' or '~' character and it cannot
contain a '?' character.
If I remove the second configuration,
https://localhost:44300/?type=promotion
wouldn't be accepted. -> Show 404 page.
My question is: Is there a way to config route URL start with '/' (none controller, none action)?
Your route is misconfigured, as the error states it cannot begin with a /, and for the home page it doesn't need to. In that case it should be an empty string.
routes.MapRoute(
name: "default",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
However, it is a bit unusual (and not SEO friendly) to want to map more than one route to the home page of the site as you are doing.
It is also unusual to do a redirect to a home page, which does an additional round trip across the network. Usually routing directly to the page you want will suffice without this unnecessary round trip.
routes.MapRoute(
name: "homepage",
url: "home/index",
defaults: new { controller = "Home", action = "Index", type = "promotion" }
);
routes.MapRoute(
name: "default",
url: "/",
defaults: new { controller = "Home", action = "Index", type = "promotion" }
);
// and your action...
[HttpGet]
public ActionResult Index(string type)
{
return View();
}
I am having trouble implementing the routing in MVC 5. While debugging the expected url(e.g. http://localhost/Download/Blog/1cf15fe6033a489a998556fedeab20a2/Test/1cd15fe6033a489a998556fedeab20a2) causes the correct method on the Download controller to be called however the did and fid are always null. What am I doing wrong? I also tried removing the Download route and defining the routes in the controller with the following attributes:
[RoutePrefix("Download")] //on the controller
[Route("{action}/{did:guid}/Test/{fid:guid}")] //on the Blog Action
Here is what I have in my RouteConfig.cs:
routes.MapRoute(
name: "Download",
url: "Download",
defaults: new { controller = "Download", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
here is my controller:
[Route("{action}/{did}/Test/{fid}")]
public class DownloadController : Controller
{
public ActionResult Index()
{
return Redirect(HandleBadResponse(webResponse));
}
[Route("{action}/{did}/Test/{fid}")]//nope
public ActionResult Blog(HttpRequestMessage request,string did,string fid)
{
string server = Request.ServerVariables["SERVER_NAME"];
string pathStr = #"\\mypath\1cf15fe6033a489a998556fedeab20a2.xls";
byte[] fileBytes = System.IO.File.ReadAllBytes(pathStr);
string fileName = "test.txt";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
I got the expected result by adding the following to my RouteConfig.cs I placed this route at the top of my RegisterRoutes method, I think you should go from most detailed route to the least detailed route:
routes.MapRoute(
name: "DownloadBlogAttachment",
url: "Download/Blog/{did}/fid/{fid}",
defaults: new { controller = "Download", action = "Blog"}
);
I removed the Route attributes in my controller as well.
We have a route config like so:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "About",
url: "{controller}/{action}/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Contact",
url: "{controller}/{action}/{contactId}",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
You will notice that there are two routes that have one mandatory extra parameter. The routes About and Contact.
In our app we have two urls
www.myapp.com/Home/About/2 which works fine.
But when we navigate our browser to www.myapp.com/Home/Contact/5 we get the dreaded routing exception:
The parameters dictionary contains a null entry for parameter 'contactId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Contact(Int32)' in 'RoutingTest.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
If we change the sequence of the routing so that it looks like so:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Contact",
url: "{controller}/{action}/{contactId}",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "About",
url: "{controller}/{action}/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Then the Contact url works but the About url does not.
The HomeController looks like this:
public class HomeController : Controller {
public ActionResult Index() {
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About(int aboutId) {
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact(int contactId) {
ViewBag.Message = "Your contact page.";
return View();
}
}
What this seems to imply is that two routings cannot have the same number of parameters regardless of the name of the Controller Action. If the two controller actions have a parameter with the same name, then all works fine. I know I can start doing very hacky things to work around this problem such as calling all parameters the same name or giving the actions meaningless parameters to change the number of parameters but I would actually like to know what is happening under the hood.
How do I solve this problem?
The root (no pun intended) of your issue ISN'T that routes can't have the same number of params. They can. The issue is that the routing engine will select the first route that matches the incoming request. Your routes are only different by the defaults, and pattern matching-wise they are exactly the same. So in each and every case you should be hitting the Contact route.
It looks like you are trying to have different routes based on the action. Which I can't actually see why you NEED.
You CAN use the following for that effect.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Contact",
url: "Home/Contact/{contactId}"
);
routes.MapRoute(
name: "About",
url: "Home/About/{aboutId}"
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
However. I HIGHLY recommend against this approach, as your "default" route would be the Contact route. This means that (under Razor) the #Html.ActionLink() and related methods will be...wrong.
Honestly, it should just work perfectly if you actually just use...
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 }
);
}
Specify controller and/or action in a route explicitly to allow routing to pick correct route:
routes.MapRoute(
name: "About",
url: "{controller}/About/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
You also can add constraints to parameters to distinguish between routes, but it looks like in your case both actions have the same integer parameter.
Couldn't you just delete your custom routes and just reuse the {id} parameter (turn {contactId} and {aboutId} into just "id" in your action code)?
public class HomeController : Controller {
public ActionResult Index() {
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About(int id) {
int aboutId = id;
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact(int id) {
int contactId = id;
ViewBag.Message = "Your contact page.";
return View();
}
}