Asp.Net Routing - Display complete URL - c#

I have a domain "http://www.abc.com". I have deployed an ASP.net MVC4 app on this domain. I have also configured a default route in RouteConfig.cs as shown below
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "MyApp", action = "Home", id = UrlParameter.Optional }
);
The above mapping ensures that anyone attempting to visit "http://www.abc.com" is automatically shown the page for "http://www.abc.com/MyApp/Home"
Everything works as expected but the address bar in the browser shows "http://www.abc.com" instead of "http://www.abc.com/MyApp/Home". Is there any way to force the browser to show the complete URL including the controller and Action?

One option would be to set your default route to a new controller, maybe called BaseController with an action Root:
public class BaseController : Controller
{
public ActionResult Root()
{
return RedirectToAction("Home","MyApp");
}
}
and modify your RouteConfig to point to that for root requests:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Base", action = "Root", id = UrlParameter.Optional }
);

You'll need to do some kind of url rewriting. Probably the quickest way is to add a RewritePath call to your BeginRequest in Global.asax. In your case it'd be something like this:
void Application_BeginRequest(Object sender, EventArgs e)
{
string originalPath = HttpContext.Current.Request.Path.ToLower();
if (originalPath == "/") //Or whatever is equal to the blank path
Context.RewritePath("/MyApp/Home");
}
An improvement would be to dynamically pull the url from the route table for the replacement. Or you could use Microsoft URL Rewrite, but that's more complicated IMO.

Just remove the default parameters, it's been answered here:
How to force MVC to route to Home/Index instead of root?

Related

ASP.NET MVC RedirectToAction not redirecting to Index of another controller

In my Account/Login controller method, I have something like:
var classA = GetObject(); //actual code omitted
switch(classA.PropA)
{
case 1:
return RedirectToAction("Action2", "Registration");
//more case code omitted
default:
return RedirectToAction("Index", "Registration");
}
All the cases work fine in the switch block except the default where it's suppose to go to Index in RegistrationController. Instead of that, it takes me to localhost:port/Registration, where the action Index is omitted.
It works fine if the ActionName is changed to something else - Index2 for example. Also works fine if the controller name is changed to something else.
RouteConfig is
just the auto-generated code from creating the project, which is as follows:
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 }
);
}
Thanks in advance.
There is nothing wrong with the route setting the reason it does not include Index in the URL because according to default route
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
when you enter /Registration the route already knows the default action which is index so it does not add /index in URL and about
403.14 forbidden
if you look at this post HTTP Error 403.14 - Forbidden - MVC 4 with IIS Express it could be because you might have a file or folder named Registration in the project directory
If you use the RedirectionToAction("Index","ControllerName");
it will redirect you with the default mapping config to localhost:port/ControllerName
and in your case if you execute the RedirectionToAction("Index","ControllerName"); it will redirect you to
localhost:port/Registration
Try to use on
return RedirectToAction("Index");
and in RouteConfig you can route Action "Index" to Controller "Registration"
like
routes.MapRoute("Index", "Index", new { controller = "Registration", action = "Index" });

C# ASP:NET MVC back end - Change from React Router v4 HashRouter to BrowserRouter results in 404 on refresh

I'm currently using HashRouter and it works really well. However I would like to be able to use the # on sub routes as well for linking to paragraphs. For example /details#Summary. As a benefit I will also get cleaner URLs and if needed I can get some SEO.
Works and gives correct results on refresh/direct link.
<HashRouter>
<App />
</HashRouter>
Works but gives 404 on refresh/direct link.
<BrowserRouter>
<App />
</BrowserRouter>
I understand that the problem here is my routing in .Net and I need to change it. What do I need to do? I have a default route but it does not get hit.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
First remove the standard routes.MapRoute that is shown above and then add this:
routes.MapRoute("Client", "{*anything}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Now any route will render your default action.
Optional:
If you have a controller with attribute routing, example:
[RoutePrefix("Home")]
public HomeController : Controller {
//GET Home/Index
[HttpGet]
[Route("Index")]
public ActionResult Index() {
return View();
}
}
You also need to add:
routes.MapMvcAttributeRoutes();
The thing is that when you change that, asp.net keeps trying to match a route from for details.
What you need to do is create a route that matches all paths, so that it returns the default one, eg: home/index
This is the route I use:
routes.MapRoute(
"Default",
"{*url}",
new { controller = "Home", action = "Index" });
That will give control to the browser to math the paths after '/'

MVC routing vs. partial class

I have a request controller that is getting out of hand, and I want to divide the actions on several controllers while maintaining a clean URL. I'm trying to experiment with routing, but without success. I've read some examples and tutorials on routing, but, though I understand the examples, nothing seems to apply to my case, and I feel non the wiser. What I want is for the URL Requests/Approval to be handled on my ApprovalController instead of my RequestController, so I wrote the following.
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
);
routes.MapRoute(
"Approval",
"Request/{controller}/{action}",
new { controller = "Approval", action="Index", id = "" }
);
}
But it's not working. Why? I have a folder in the my Views called Approval, and in there I have a file called Index.cshtml. How should I code the MapRoute?
Edit
I added all the routes I've got
You need to swap the two MapRoute statements, like so:
routes.MapRoute(
"Approval",
"Request/Approval/{action}",
new { controller = "Approval", action="Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
The reason it is currently not working is because the first statement ('Default' route name) is getting matched before the second one is even evaluated.
In addition (as noted in my above example,) you need to remove '{controller}' in the Approval route and replace with 'Approval'... unless you specifically want the URL /Request/{ANY controller}/{action} to go through, which I doubt. From your question it seems you only want /Request/Approval/ to go to your Approval controller.
Don't forget to keep the Default route at the bottom, so as to match your other controllers and actions. It serves as a catch-all should no other matches exist.
The order you map your routes matters. Move the second route before the default route.
You will still have a problem though, as any thing /request/something will look for the SomethingContoller. To fix this, change your route to this:
routes.MapRoute(
"Approval",
"Request/Approval/{action}",
new { controller = "Approval", action="Index", id = "" }
);

MVC3 and Rewrites

I'm writing an MVC3 application that will need to make use of URL rewriting in the form of http://[server]/[City]-[State]/[some term]/ .
As I understand it, MVC3 contains a routing engine that uses {controler}/{action}/{id} which is defined in the Global.asax file:
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
);
}
Traditionally (in a non-MVC app), I would use some URL rewriting flavor to decode a url such as http://www.myserver.com/City-State/somesearch/ to querystring parameters that look something like this:
http://www.myserver.com/city=City&state=State&query=somesearch
Keep in mind that this request would be coming from http://www.myserver.com/Home
Can this can be accomplished without having to specify a controller... something like this:
routes.MapRoute(
"Results",
"{city}-{state}/{searchTerm}",
new { controller = "Results", action = "Search" }
);
... or is it really best to have the controller listed?
How do you handle this in an MVC3 environment?
Thanks.
URL rewriting in asp.net MVC3:-
you can write code for url rewriting in Global.asax file :-
//Default url
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"",
new { controller = "Home", action = "Index", id = "" }
);
//others url rewriting you want
RouteTable.Routes.MapRoute(null, "Search/{City_State}/{ID}", new { controller = "Home", action = "Search" });
Check out these two answers:
ASP.NET MVC Routes: How to define custom route
Defining custom URL routes in ASP.Net MVC
Summary:
Specify custom routes before the default one.
Define specific routes before general as they may match both.
Default values are optional.
Specify default Controller and Action in the default parameter object.
You can do this by registering route in Global.asax file, but order to register the Route is important you must be register first Old route then new one.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// for Old url
routes.MapRoute(
"Results",
"{city}-{state}/{searchTerm}",
new { controller = "Results", action = "Search" }
);
// For Default Url
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

MVC Routing problem

I am learning MVC and I need to understand why it doesn't work the way it should.
Here is my routing :
public static void RegisterRoutes(RouteCollection routes)
{
// Note: Change the URL to "{controller}.mvc/{action}/{id}" to enable
// automatic support on IIS6 and IIS7 classic mode
//http://localhost/store/category/subcategory/product
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Category", // Route name
"store/{category}/{subcategory}", // URL with parameters
new
{
controller = "Catalog",
action = "Index",
category = "Featured Items",
subcategory = "All Items"
}
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new { controller = #"[^\.]*" } // Parameter constraints
);
}
The way I understand routing I should see the following url when I start the web app :
http:/localhost/store/
What I get is the second route....
Furthermore if I change the second route to "home/{action}/{id} it doesn't catch any routes.
Could you help me understand this please..Thanks
Routes do not specify default URL; the default URL is handled by your app. Routing specifies that when it sees http://localhost/store/bikes/mountain, it will use the catalog controller. But that doesn't specify the default URL; you have to enter that in the project properties.
I would recommend not changing the second one because unless you are creating groupings for all of your controllers, it's best to have the default as it is so you can catch all URL's. Your change to the second one would require the url to be:
http://localhost/home/home/index to match the HomeController's index action, whereas the default setup catches http://localhost/home/index...
Does that make sense?
Try this: http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

Categories

Resources