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

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

Related

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

How to set another page as default page in ASPNET BOILERPLATE MVC5?

I'm trying change default page when I start my app, but I can't do it. When I start the first page is "Account/Login", but I need it changes to other pages.
In project web I'm doing this: * HomeController: Add HomePage actionResult * View/Home: Add View to Home with name HomePage
In app_start/routeconfig.cs
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "HomePage", id = UrlParameter.Optional } );
Also, i changed the properties of web project to specify page: Home/Homepage, but it's not working
Results in both options arent work
Template: Boilerplate with ASP.NET MVC 5 + Zero Module
i'm new with abp.
In HomeController.cs, comment out (or remove) the [AbpMvcAuthorize] attribute:
// [AbpMvcAuthorize]
public class HomeController : AbpProjectNameControllerBase
You can apply [AllowAnonymous] for specific actions to suppress authentication/authorization:
[AbpMvcAuthorize]
public class HomeController : AbpProjectNameControllerBase
{
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
public ActionResult HomePage()
{
return View();
}
}
See the documentation on MVC Controllers.
Maybe it's better to use a different controller for anonymous actions. Create a new controller called WelcomeController. Do not add a AbpMvcAuthroize attribute. Then set your default route as Welcome/Index.

Routes mapping in MVC 5

I'm trying to understand how the route config works in the MVC 5.
I have the following structure for my application:
BaseCRUDController
public class BaseCRUDController<TEntity, TEntityViewModel> : Controller
where TEntity : class
where TEntityViewModel : class
{
private readonly IBaseService<TEntity> baseService;
public BaseCRUDController(IBaseService<TEntity> service)
{
this.baseService = service;
}
[HttpGet]
public virtual ActionResult Index()
{
IList<TEntityViewModel> entities = baseService.FindFirst(10).To<IList<TEntityViewModel>>();
return View(entities);
}
}
CountriesController
[RouteArea("management")]
[RoutePrefix("countries")]
public class CountriesController : BaseCRUDController<Country, CountryViewModel>
{
private readonly ICountryService service;
public CountriesController(ICountryService service)
: base(service)
{
this.service = service;
}
}
What I'm trying to do is simple: http://myapplication.com/management/countries.
I have many others controllers that the superclass is the base controller. I'm doing this way to avoid code repetition, since that the controllers have similar structure.
The problems are:
I can't reach the url that I want (/management/countries)
I don't know how to configure my Home Controller, because I want that it could be reached by http://myapplication.com
How could I fix these problems?
My route config is like that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
After a little playing around I managed to get it to work.
The problem is when you are using attribute routing there are no default route parameters assigned.
For example in your Default route the defaults are controller = "Home", action = "Index". So if you were to call http://myapplication.com/ the routing engine will automatically default to /Home/Index/ and so on.
However the attribute route has no way of knowing you want to default to the Index action (or any other action for that matter).
To solve the issue add the Route attribute to the CountriesController like this:
[RouteArea("management")]
[RoutePrefix("countries")]
[Route("{action=Index}")] // this defines the default action as Index
public class CountriesController : BaseCRUDController<Country, CountryViewModel>
{
private readonly ICountryService service;
public CountriesController(ICountryService service)
: base(service)
{
this.service = service;
}
}
Also for future reference Phil Haack's Route Debugger is extremely helpful for figuring out routing issues.
Have you defined Area (management) for your controllers?
if you try without Area, is that getting redirect properly?

Redirect using routing in MVC

I have ASP.NET MVC application.
I want my application to redirect from
example.com/Register
to
example.com/Account/Register
How can I do it with routes? It makes little sense to me to make controller only for this one task
public class RegisterController : Controller
{
public ActionResult Index()
{
return RedirectToAction("Register", "Account");
}
}
You don't need a redirect. You need a custom route
Add this route first (above "Default")
routes.MapRoute(
"Register",
"Register",
new { controller = "Account", action = "Register" }
);
This solution will leave the user on URL example.com/Register, but instantiate Controller Account, execute ActionResult Register, and return View Account/Register.

static routing returning 404?

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

Resources