static routing returning 404? - asp.net

I'm trying to create a static route as follows:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Hire",
url: "Hire/{gender}",
defaults: new { controller = "Hire", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
however, when I try access /Hire/Female, for instance, IIS throws a 404 error, as I was reading about routing I noticed routes are usually written as {controller}/{action}/{something}, is it mandatory to have {controller} and {action} on my route?
here's the code for the controller:
public class HireController : Controller
{
[HttpGet]
public ActionResult Index(string gender)
{
return View();
}
}
and I have a file named /Views/Hire/Index.cshtml
what I was trying to achieve is to route requests from /Hire/Male and /Hire/Female to the Index action of my HireController but I have the feeling I'm forgetting something since I've tried in different ways and always have a 404 returned
Update 1
I installed the RouteDebugger from http://www.codeproject.com/Articles/299531/Custom-routes-for-MVC-Application and it just shows the "basic" routes from MVC ({resource}.axd/{*pathInfo} and {controller}/{action}/{id}), it doesn't show the route I mapped

It turns out I added the RegisterRoutes method in the wrong location, I thought I had to include that method inside Global.asax, I guess prior to MVC4 the Global.asax was the right location, however, on MVC4 I have to map the routes using the file located in /App_Start/RouteConfig.cs

Related

How to redirect page from default route to custom one in MVC application?

I would like to know whether there is a way to redirect page from "~/ControllerName/Index" to custom route like "~/example-custom" without using 301 redirect in URL rewrite module.
I have used routing attribute:
[Route("example-custom")]
public ActionResult Index()
{
return View();
}
But with this routing attribute "~/ControllerName/Index" is no more. When users go to "~/ControllerName/Index", page does not exist on that route. I would like redirect users to "~/example-custom" when they want to access page.
So, what I would like in shorter terms is to browser display link "something.com/example-custom" and not "something.com/ControllerName/Index". But also accessing "something.com/ControllerName/Index" would redirect automatically to "something.com/example-custom".
Add custom route into RouteConfig.cs File
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "example-custom",
url: "{example-custom}/{id}",
defaults: new { controller = "YourControllerName", action = "YourActionName", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

Why A simple method having two arguments is not working in ASP.NET MVC?

My controller:
public class AjaxController : Controller
{
private readonly IGenerationUnitMobileService _generationUnitMobileService;
public AjaxController(IGenerationUnitMobileService generationUnitMobileService)
{
_generationUnitMobileService = generationUnitMobileService;
}
public IActionResult MobileExistToAnotherGenerationUnit(String mobile, long generation_unit_id)
{
//ViewBag.Result = _generationUnitMobileService.MobileExistToAnotherGenerationUnit(mobile,generationUnitId);
return View();
}
}
And My view file is very simple:
#model PgcgSms.WebSite.Models.GenerationUnitMobileViewModel
#{
Layout = "~/Views/Shared/_Ajax.cshtml";
}
#ViewBag.Result
This is so much straight forward. But when I browse at: http://localhost:57216/Ajax/MobileExistToAnotherGenerationUnit/01719393045/1
I am getting the following error message:
This localhost page can’t be found
No webpage was found for the web address: http://localhost:57216/Ajax/MobileExistToAnotherGenerationUnit/01719393045/1
Search Google for localhost 57216 Ajax Mobile Exist To Another Generation Unit 01719393045
HTTP ERROR 404
I checked the view file and spellings several times. Whats wrong with my code?
In the RouteConfig.cs file you will have to specify the default route.
For Example:
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 = "AjaxController", action = "MobileExistToAnotherGenerationUnit", id = UrlParameter.Optional }
);
}
}

ASP.NET MVC 5 not seeing "{id}" route in controller

I've created a new ASP.NET MVC 5 project in Visual Studio 2015 Update 3, and everything is pretty standard. I have this controller:
public class UsersController : BaseController
{
[HttpGet]
public async Task<ActionResult> Newest()
{
var newestUsers = await Database.Users.OrderByDescending(u => u.ID).Take(100).ToListAsync();
return View(newestUsers);
}
[HttpGet]
[Route("{id}")]
public async Task<ActionResult> GetUser(long id)
{
var user = await Database.Users.FindAsync(id);
return View(user);
}
}
My BaseController derives from regular MVC Controller and it contains some common properties for my app. Nothing special.
When I go to /users/newest the appropriate page loads, but when I go to /users/1 I immediately get a 404 not found error. I've tried changing the route to ~/{id} but no avail. My route configuration is the standard, auto-generated one, I haven't touched 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 }
);
}
}
Why am not hitting the GetUser action?
UPDATE: For some reason, it started not working again. I didn't do anything. It was working after I've added routes.MapMvcAttributeRoutes();, it's still there but I started getting 404 again.
Okay I have no idea how it went away (or why it wasn't there) but I was missing the routes.MapMvcAttributeRoutes(); method in route configuration. Adding that method fixed the issue.
UPDATE: I've also needed to add RoutePrefix to get the routes working, and I have to explicitly add the correct route for any actions that have arguments. It's a pity that MVC can't map them by themselves.
Get ride of your additional Id routing above getuser - this isn't needed.
Your route is incorrect - it should be users/getuser/1

ActionLink ignoring attribute routing settings

I have a TextObject controller, which is meant to be accessed by "~/umt/text/{action}/{id?}", as defined in the controller using attribute routing, but the action link:
#Html.ActionLink("Index", "Index", "TextObject")
ignores Attribute Routing and uses the Conventional routing definitions, producing ~/TextObject/ instead of the desired ~/umt/text/
the TextObjectController:
[Authorize]
[RouteArea("umt")]
[RoutePrefix("text")]
[Route("{action=index}/{id?}")]
public class TextObjectController : Controller
{
.....
public async Task<ActionResult> Index()
{
return View(await db.TextObjects.ToListAsync());
}
.....
}
My route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enable Attribute Routing
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Is there any additional configuration required on the controller to make the action link work or does it not work with attribute routing?
I'd like to keep it simple, and it routes correctly going directly through the url, but the ActionLink helper seems to not like something about it.
I can't see that you specify your defauld area it RouteConfig so your action link should look like:
#Html.ActionLink("TextObject", "Index", "Index", new { area = "umt" }, null)

Routing to an aspx page on a project with webforms and MVC

I've added MVC to an existing webforms project that I've been working on as I'm looking to slowly migrate the project, however, during the change over period I need to be able to access both, but have it default to the aspx pages.
When it comes to registering the routing, I currently have this in place:
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("Backup", "{*anything}", "~/Default.aspx");
routes.MapRoute(
"MVC",
"{controller}/{action}/{id}",
new { controller = "Test", action = "Index", id = 1 }
);
}
However, when I have it setup like this, even if I put in a URL that I know refers to a controller/action combination (e.g. Test and Index from the last line of this), it still redirects the user to the Default.aspx page.
I've tried changing this over to the following:
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"MVC",
"{controller}/{action}/{id}",
new { controller = "Test", action = "Index", id = 1 }
);
routes.MapPageRoute("Backup", "{*anything}", "~/Default.aspx");
}
Here, the user can specify a page or specify a controller/action, but if they do not include any controller/aspx page, it defaults to the default MVC route, whereas I need it to default to the webform Default.aspx.
How would I get around the situation so that if no page/controller is specified, it directs to ~/Default.aspx, and if a controller is specified, it directs to that controller?
I tried experimenting with your scenario where in i have an existing web forms application and have added mvc to it. Basically i have come across two solutions.
First: you can ignore adding routes.MapPageRoute to route config; this is what i have done
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.EnableFriendlyUrls();
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
}
Please notice that i have excluded value for controller in the defaults. Now even if there is a match and if there is not controller present by that name then the request will fall back to the regular ASP.Net pipeline looking for an aspx page. With this approach you could request urls like http://localhost:62871/ or http://localhost:62871/Home/Index or http://localhost:62871/Home/ or http://localhost:62871/About.aspx
Second:: In this approach you can create an area under Areas folder for your new MVC based work and leave the RouteConfig in App_Start to its default so that it looks like following.
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.EnableFriendlyUrls();
}
}
And then in your Area registration class define route as in following example .
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Hope that helps. Thanks.

Resources