ASP.NET MVC 5 route config - c#

I have 2 routes:
college/{courseId}/{classId}
college/{courseId}
But sometime when I try to input the 1st url type like college/course1/class2, it go to the 2nd action.
Can I fix route configuration to do it exactly? Here is my code:
[Route("college/{courseId}/{classId}")]
public void ActionResult example1(string courseId, string classId) {
return View();
}
[Route("college/{courseId}")]
public void ActionResult example2(string courseId) {
return View();
}
RouteConfig.cs file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.MapMvcAttributeRoutes();
//Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

This may be helpful to you.
https://www.nuget.org/packages/routedebugger/
It will show you what routes are matched.
I suspect that they both are matched but are added in the incorrect order.
It may be as simple as inverting the order in which they are adding or making them more specific. ( making the params required)

I recommend you to define only one route and have only one action with an optional parameter:
[Route("college/{courseId}/{classId?}")]
public void ActionResult example1(string courseId, string classId) {
// Do classId null check if necessary
return View();
}
Please notice, there is a question mark after classId parameter in route definition.

Related

How to configure routeConfig.cs to take input directly after root domain

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

check second parameter in asp.net

I am new in c# mvc, and I am trying to make a route with multiple parameters that looks like this:
controller/action/parameterOne/parameterTwo
but in some cases I'm gonna just use one of them so the route will look like this:
controller/action/parameterOne
here is my RouteConfig.cs
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:"Default2",
url: "{controller}/{action}/{category}/{id}",
defaults: new { controller = "Home", action = "Index", category = UrlParameter.Optional, id = UrlParameter.Optional }
);
}
now in my controller's action I need to check if there is only one parameter or two so I can return a different view for each condition, here is the controller:
[HttpGet]
public ActionResult someAction(string category, string id)
{
if (String.IsNullOrWhiteSpace(id))
{
return View("viewOne");
}
else
{
return View("ViewTwo");
}
}
the problem is that the if statement is not full working? because if the conditoin is this: String.IsNullOrWhiteSpace(id)
and if I write controller/action/parameterOne this return the ViewOne
but if I write controller/action/parameterOne/parameterTwo also return the ViewOne
but now if a invert the condition and I write !String.IsNullOrWhiteSpace(id) both urls return ViewTwo.
So does any one have any idea why is that happening?
Do you have any objection to only using the default route? The only drawback that comes to mind is if you really want your url to look a certain way in which case you may need to define multiple routes as youre trying to do. However, the following should work with only the default route:
//note controller actions will default to HttpGet if no data annotation is explicitly supplied. Also, action names generally begin uppercase by convention
public ActionResult SomeAction(string category, string id = null)
{
if (String.IsNullOrWhiteSpace(id))
{
return View("viewOne");
}
else
{
return View("ViewTwo");
}
}
the various requests you mentioned would look like:
www.myhost.com/controller/someaction?category=parameterOne&id=parameterTwo
or
www.myhost.com/controller/someaction?category=parameterOne

MapMvcAttributeRoutes ignores [NonAction] attribute

Any public method that returns string, bool or ActionResult in a Controller class is seen as an Action. If you want to mark it as not being an action, you can use the [NonAction] attribute:
[NonAction]
public bool PubMethod( out string param1)
{
return false;
}
this works fine if you do not use attribute mapping routing. The app starts and the method is not seen as an action (it cannot be used as such, since it has an out param), everybody is happy.
If instead you use attribute routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
the [NonAction] attribute is ignored, and the app crashes on the line
routes.MapMvcAttributeRoutes();
complaining that the PubMethod action cannot be called because it has a by ref parameter.
I can't find any mention of this in the docs. Any way to mark a public method as non action when attribute routing is used?

MVC Default route with nullable id not working as expected

A simple routing scenario is not working for me.
my route registration looks like this
context.MapRoute(
"Users_default",
"Users/{controller}/{action}/{id}",
new { action = "Index", id= UrlParameter.Optional });
and i am expecting it to honor the requests for
users/profile/
users/profile/1
users/profile/2
with the following controller
public class ProfileController : Controller
{
public ActionResult Index(int? id)
{
var user = id == null ? (UserModel)HttpContext.Session["CurrentUser"] : userManager.GetUserById((int)id);
return View(user);
}
}
it works for users/profile but not for users/profile/1
i've tried few different things but i know the answer must be simple, its just my lack of knowledge, what am i missing here.
i dont want index to appear. i want to use the same method for both users/profile/1 and users/profile/
Then don't put action into your URL.
context.MapRoute(
"Users_default",
"Users/{controller}/{id}",
new { action = "Index", id= UrlParameter.Optional });
The route you have defined will not allow index to be optional because it is followed by another parameter (in this case "id"). Only the last parameter can be optional on all but the default route.
This is because your route interprets as:
{controller: "profile", action: "1"}.
You need to point you details action url explicit, something like this:
users/profile/index/1
You can use Attribute routing
The code would look like
public class ProfileController : Controller
{
[Route("users/profile/{id}")]
public ActionResult Index(int? id)
{
var user = id == null ? (UserModel)HttpContext.Session["CurrentUser"] : userManager.GetUserById((int)id);
return View();
}
}
And you have to modify your RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// This will enable attribute routing in your project
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
So now you can use users/profile for your default behaviour and users/profile/ for a specific profile.

Routing optional parameters in ASP.NET MVC 5

I am creating an ASP.NET MVC 5 application and I have some issues with routing. We are using the attribute Route to map our routes in the web application. I have the following action:
[Route("{type}/{library}/{version}/{file?}/{renew?}")]
public ActionResult Index(EFileType type,
string library,
string version,
string file = null,
ECacheType renew = ECacheType.cache)
{
// code...
}
We only can access this URL if we pass the slash char / in the end of url, like this:
type/lib/version/file/cache/
It works fine but does not work without /, I get a 404 not found error, like this
type/lib/version/file/cache
or this (without optional parameters):
type/lib/version
I would like to access with or without / char at the end of url. My two last parameters are optional.
My RouteConfig.cs is like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
How can I solve it? Make the slash / be optional too?
Maybe you should try to have your enums as integers instead?
This is how I did it
public enum ECacheType
{
cache=1, none=2
}
public enum EFileType
{
t1=1, t2=2
}
public class TestController
{
[Route("{type}/{library}/{version}/{file?}/{renew?}")]
public ActionResult Index2(EFileType type,
string library,
string version,
string file = null,
ECacheType renew = ECacheType.cache)
{
return View("Index");
}
}
And my routing file
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// To enable route attribute in controllers
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
I can then make calls like
http://localhost:52392/2/lib1/ver1/file1/1
http://localhost:52392/2/lib1/ver1/file1
http://localhost:52392/2/lib1/ver1
or
http://localhost:52392/2/lib1/ver1/file1/1/
http://localhost:52392/2/lib1/ver1/file1/
http://localhost:52392/2/lib1/ver1/
and it works fine...
//its working with mvc5
[Route("Projects/{Id}/{Title}")]
public ActionResult Index(long Id, string Title)
{
return view();
}

Categories

Resources