Customize URL in MVC not working - asp.net-mvc

I am new in Asp.net MVC. I am struck at my Customize URL Routing problem.
I have created my Controller named "Customer" and action as "DisplayCustomer".
In Global.asax.cs page,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Customer",
action = "DisplayCustomer",
id = UrlParameter.Optional
}); // Parameter defaults//, new { Code = #"\d{1001,1002}" }
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}
}
I don't know what wrong in it,it is always showing
as
http://localhost:50415/Views/Customer/DisplayCustomer.aspx
not as
http://localhost:50415/Customer/DisplayCustomer
Am I missing something to make it this to work?

Replicated your problem
Select Project Properties
Select Web Tab
Now, See the highlighted part in screen shot below
Original Version
Modified Version
Removed the View Directory and .cshtml extension. This happened because you set the start Page.
Selecting the Current Page will fix your issue

This url: http://localhost:50415/Views/Customer/DisplayCustomer.aspx is probably opening up in your Browser when you run/debug your project while the current active document in Visual Studio is the DisplayCustomer view, try to close this document and re-run the project (i think the problem is fixed for MVC 4 projects).
More importantly, your Routes are not correctly defined. if you want to access your Action using the default pattern ({Controller}/{Action} and in your case /Customer/DisplayCustomer) you don't have to write any custom route, just leave the default route as is:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL pattern
new { Id = UrlParamter.Optional });
Now, the standard way to get the Url pointing to your Action (from within your Controller/View) is to use the Url.Action method. for example: Url.Action("DisplayCustomer", "Customer").

Change "Views" to "Default"
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Customer",
action = "DisplayCustomer",
id = UrlParameter.Optional
}); // Parameter defaults
}

Related

run a website project on visual studio failed in local by http 404 not found page error

I have been working on a project and I left it for about one week,when I came back to it and I tried to run the project with Ctr+F5 , it redirect to a URL which is not defined in route config. like this http://localhost:53771/Views/Home/Index.cshtml and confronted with HTTP 404: not found Error. while my route config is like this BUT IT WORKS FINE IF I TYPE THE CORRET URL MYSELF in front of the r+F5 , it redirect to a URL which is not defined in route config. like this http://localhost:53771
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I started debugging the project and it seems the project never come to my HomeController . I just have one controller named Home, and when I removed all the codes of my Home controller it still act the same. and the other thing which it seems wrong, it creates the URL http://localhost:53771/Views/Home/Index.cshtml even before it comes to RegisterRoutes function. the problem is all local and here is my global.asax if needed. I appreciate any help
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace ML_Projectname
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcHandler.DisableMvcResponseHeader = true;
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Powered-By");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
HttpContext.Current.Response.Headers.Remove("Server");
}
}
}
I don't believe there is any issue with your routing or your application. Visual Studio's default start action (view by right clicking project -> selecting properties -> selecting Web) is "Current Page". If you're viewing a razor view (such as your /Views/Home/Index.cshtml) at the time you run the project in visual studio, visual studio will try to navigate to this resource directly. Directly requesting a razor view is not valid in the context of an MVC application and you end up seeing the 404 error.
To avoid this, you can set the start url to a specific URL (ex: http://localhost:53771) or even simpler, open and view one of the server side files (ex: HomeController.cs) before running your project via Visual Studio.
tldr version: this is an issue with a setting you have in visual studio, not an issue with your application code

Adding new controller gives HTTP error

In my ASP.NET MVC 5 application, I used to have a controller called Alpha, which I played around with for a while, and then ended up deleting it. Now, I've decided that I want to have another controller called Alpha, with different functionality from before.
So, I have added a new controller, named it Alpha, and added an Index view for this controller. But when I go to localhost:IP/Alpha, I get the following error:
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
All I have done though, is add the controller with the code, and then add an Index view with the default code.
The strange thing, is that if I add a controller and a view in the same way, but call it anything other than Alpha, then the application works as would be expected, and Alpha's Index view is displayed.
So I am assuming there is something remaining in the system from the old Alpha controller (which may have originally been buggy, I cannot remember), which is conflicting with this new Alpha. Any ideas on how I might investigate this further?
As requested by Jason Evans, here is my Global.asax.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Poseidon
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
As requested by Jason Evans, here is my RoutConfig::RegisterRoutes function:
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 }
);
}

Web API Attribute Routes in MVC 5 exception: The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized()

On an MVC 5 with Web API I have the following, using only Attribute Routes:
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" }); // TODO: Check for Apple Icons
RouteTable.Routes.MapMvcAttributeRoutes();
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
AreaRegistration.RegisterAllAreas();
In the RouteTable all the MVC routes were created ... But not the API ones ...
I checked the RouteTable.Routes and I see an exception:
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at
System.Web.Http.Routing.RouteCollectionRoute.GetEnumerator() at
System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
For testing this I added only two Web Api actions to the project:
[RoutePrefix("api")]
public class StatApiController : ApiController {
[Route("stats/notescreateddaily"), HttpGet]
public IHttpActionResult NotesCreatedDaily() {
// Some code
}
[Route("stats/userscreateddaily"), HttpGet]
public IHttpActionResult UsersCreatedDaily() {
// Some code
}
}
Am I missing something?
Thank You,
Miguel
The solution is in fact replacing:
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
By:
GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());
That was a change in Web API 2.
The solution is to call GlobalConfiguration.Configuration.EnsureInitialized(); after all your Web API related configuration is done, but I am curious as to why your registrations look like this...What kind of project template did you use to create the MVC5 project?...The predefined templates that come with Visual Studio has a structure which helps minimize route ordering problems and so would recommend using them, so wondering why your configuration structure looks like that...
I am having the same problem after I upgrade all my web services project using ASP.Net Web API 4.0 to 4.5 and using Web API 2.2 with Cors library. I managed to successfully solve the problem. What I did was eliminating or commenting out the following statement at the RouteConfig.cs file at App_Start folder:`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace myNameSpace.Configurations
{
public static class RouteConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
//DON'T USE THIS. IT WILL GIVE PROBLEMS IN INSTANTIATION OF OBJECTS
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "LocationData",
routeTemplate: "dataservices/locations/{controller}/{action}/{id}",
defaults: new {action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ProfileData",
routeTemplate: "dataservices/profiles/{controller}/{action}/{id}",
defaults: new { action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
On my Global.asax.cs file I am using the old routing registration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Net.Http.Formatting;
using myNameSpace.IoC;
using myNameSpace.Configurations; // Here actually I change the protected void Application_Start() to protected void Configuration() and change the folder to configuration instead on App_Start
using myNameSpace.Controllers.ExceptionSchema;
using myNameSpace.Filters.HttpFilters;
namespace myNameSpace
{
public class WebApiApplication : System.Web.HttpApplication
{
public static void RegisterApis(HttpConfiguration config)
{
config.Filters.Add(new CustomHttpExceptionFilter());
}
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
RegisterApis(GlobalConfiguration.Configuration);
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.Register(GlobalConfiguration.Configuration);
}
}
}
Here is the reason:
Attribute Routing in Web API 2
Note: Migrating From Web API 1
Prior to Web API 2, the Web API project templates generated code like this:
protected void Application_Start()
{
// WARNING - Not compatible with attribute routing.
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
If attribute routing is enabled, this code will throw an exception. If you upgrade an existing Web API project to use attribute routing, make sure to update this configuration code to the following:
protected void Application_Start()
{
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
}
I am using the old route and I decided not to use attribute routing. So take OUT THAT statement

Having issue with multiple controllers of the same name in my project

I am running into the following error with my ASP.NET MVC 3 project:
Multiple types were found that match
the controller named 'Home'. This can
happen if the route that services this
request ('Home/{action}/{id}') does
not specify namespaces to search for a
controller that matches the request.
If this is the case, register this
route by calling an overload of the
'MapRoute' method that takes a
'namespaces' parameter.
The request for 'Home' has found the
following matching controllers:
MyCompany.MyProject.WebMvc.Controllers.HomeController
MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController
I have a HomeController in my default controller folder, with a class name of MyCompany.MyProject.WebMvc.Controllers.HomeController.
My RegisterRoutes method, in my global.asax, looks like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I then have an area called Company, with a HomeController in the default controller folder for the area, with a class name of MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController.
The RegisterArea method in the CompanyAreaRegistration file looks like:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Company_default",
"Company/{controller}/{action}/{id}",
new { area = "Company", action = "Index", id = UrlParameter.Optional }
);
}
This is all leading the error I highlighted at the beginning of this post. I am struggling trying to piece together a solution from various other posts, with NO LUCK.
Is it possible to have a HomeController in the default controllers folder and then one in EACH area? If so, do I need to make (assuming I do) changes to my configuration file to make this work?
Any help would be much appreciated!
The error message contains the recommended solution: "If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter."
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "MyCompany.MyProject.WebMvc.Controllers"}
);
This will make http://server/ go to your HomeController's Index action which is, I think, what you want. http://server/company/home will go to the Company area's HomeController's Index action, as defined in the area registration.
This is the asp.net mvc4 approach:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "RegisterNow", id = UrlParameter.Optional },
namespaces: new[] { "YourCompany.Controllers" }
);
I had renamed the namespaces, so, i only delete de folders bin and obj and rebuild, work again.
If you're using RazorGenerator, just informing the namespaces parameter could be not enough.
I got to solve adding the statement marked below at Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ControllerBuilder.Current.DefaultNamespaces.Add("MyProject.Controllers"); // This one
}
Another plausible cause of this issue could be found below:
Multiple types were found that match the controller named 'Home'
use this
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "ProjectName.Controllers" }
);
Use only the name of the project:
Public Class RouteConfig
Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
, namespaces:={"MvcAreas"})
End Sub
I had the same issue and found that the older version had created compiled files in the "bin" folder.
Once I deleted these the error disappeared.
As Chris Moschini mention the namespaces parameter may not be enough if you have two areas with same controller name with different namespaces and the default none area route will return 500 server error.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "MyCompany.MyProject.WebMvc.Controllers"}
);
It "best" to override the default route handler and add this line:
RequestContext.RouteData.DataTokens["UseNamespaceFallback"] = false;
I had this issue after I added a reference to another project that had the same routes and the problem continued after I removed the reference.
Resolved by deleting the .dll file of that added reference from the bin folder and rebuilding.
Like many others, I had this problem after creating a new MVC template project from VS2017 menu, on building the project I would get the op's error message. I then used the answer https://stackoverflow.com/a/15651619/2417292 posted earlier in this thread by cooloverride
for mvc4 projects.
This still didn't fix my issue so I renamed my Home view folder and HomeController file to be the view folder Company/ and controller file CompanyController. This then worked for me, not a fix per say but a workaround if your not stuck on having the route Home/Index my other issue was I couldn't find the reference causing the error and due to my dev platform being Azure WebApplication vs a full VM with a complete file system and IIS settings to mess with.
For MVC5 below code works for issue same controller name for different areas. You have to specify which area controller have to hit first.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "ApplicationName.Areas.AreaName.Controllers" }
).DataTokens.Add("area", "AreaName");
This issue occurred when I accidentally added
[Route("api/[controllers]s")]
instead of
[RoutePrefix("api/[controllers]s")]
to the top of my ApiController.

In ASP.NET MVC, why do I get 404 errors after Publishing my website?

I'm still new to ASP.NET MVC and I'm struggling a little with the routing.
Using the ASP.NET development server (running directly from Visual Studio), my application can find its views without any problems. The standard ASP.NET URL is used - http://localhost:1871/InterestingLink/Register
However, when I publish my site to IIS and access it via http://localhost/MyFancyApplication/InterestingLink/Register, I get a 404 error.
Any suggestions on what might be wrong?
More info...
This is what my global.asax file looks like (standard):
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
My controller is also very simple:
public class InterestingLinkController : Controller
{
public ActionResult Register()
{
return View("Register");
}
}
I figured out what was wrong. The problem was actually that IIS5 (in Windows XP) does not fire up ASP.NET when the URL does not contain a .ASPX. The easiest way to get around this is to add a '.aspx' to your controller section in global.asax. For example:
routes.MapRoute(
"Default",
"{controller}.aspx/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
Not pretty, but it will do.
Lots of things could be wrong:
Is the IIS Virtual Directory & Application set correctly?
Is the ASP.NET application being called at all? (Add some logging/breakpoiont in Application_Start and Application_BeginRequest)
Just for a start. You are going to have to apply the usual debugging approaches.
(To avoid issues like this, I rarely use the development server and just use IIS the whole time: most difficult thing is remembering to run VS elevated every time.)

Resources