MVC querystring parameter not passing through to action - c#

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

Related

Custom URL in mvc .net

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)
{
// ...
}
}

ASP.net MVC routing

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

Route URL must be started with '/'

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

Trouble getting parameters using route attributes

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.

MVC routing only applying to certain action results

Do I have to route a special route for every action result in a controller, or do you do one route, and have to live by that standard thought the controller? I thought you could make a default route, and then a special route for any instance you wanted. I keep running into a problem where one of my routes will hit my action Results correctly, but then the others no longer work. This code is probably the wrong way, but hence why I am posting it here. PLease try to clarify this for me if you can. I understand that I am suppose to be able to do {controller}/{action}/{id} for example. So that should hit Settings/GetSite/{siteid} for the following
public ActionResult GetSite(int id);
Routes configuration:
routes.MapRoute(
"SettingsUpdateEnviorment",
"{controller}/{action}",
new { controller = "Settings", action = "UpdateProperties" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
name: "ProfileRoute",
url: "Profiles/{userId}",
defaults: new
{
controller = "Profile",
action = "Index",
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Settings", // Route name
"Settings/{id}", // URL with parameters
new { controller = "Settings", action = "Index" } // Parameter defaults
);
Controller Code:
public ActionResult Index(int id)
{
return View(model);
}
public ActionResult GetSite(int enviornmentID, string name)
{
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddSite(int id)
{
return RedirectToAction("Index", new { id = id });
}
So, the URL works as expected for Settings/1 to hit the Index actionresult Index(int id). Then, when I try to do the ActionResult for GetSite(int enviornmentID, string name) using the following actionLink:
#Html.ActionLink(site.Name, "GetSite", "Settings", new { enviornmentID = Model.Enviorment.EnvironmentID, name = site.Name }, null)
It creates the URL correctly as follows: Settings/GetSite?enviornmentID=1&name=CaseyTesting2, but gives me an error stating that I am trying to send a null value to my Index(int id) actionResult. I thought that since I am using the action name and it's same params, that MVC will figure the route out? Why is this not functioning for me, or what I am doing wrong? Thanks!
I realized what I was doing thanks to this article http://www.itworld.com/development/379646/aspnet-mvc-5-brings-attribute-based-routing. I was mixing up the order, when I had everything else correct. Then I was missing the param names being identical, when everything else was correct. So I kept having minor issues when trying to find the problem out. I also switched to MVC5's attribute routing, and like it much more.
So this is my code that is now working:
RoutConfig
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "ProfileRoute",
url: "Profiles/{userId}",
defaults: new
{
controller = "Profile",
action = "Index",
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The controller code
[Authorize]
[RoutePrefix("settings")]
[Route("{action=index}")]
public class SettingsController : ZenController
{
[Route("{id:int}")]
public ActionResult Index(int id)
{
return View(model);
}
[Route("GetSite/{sitename:alpha}")]
public ActionResult GetSite(string sitename)
{
return RedirectToAction("Index");
}
Thanks again everyone! Happy coding!

Categories

Resources