Get all routes defined in global.asax - c#

I am using webformrouting in my asp.net c# application.
In my global.asax file i define a couple of routes.
My question is, how can i get a list of all routes defined from code behind (on a page)?

You can access the Routes property on the RouteTable
System.Web.Routing.RouteTable.Routes;

I create a partialView to visualize these in the site to help me from time to time (debugging).
#{
var routes = RouteTable.Routes;
}
#foreach (var route in routes)
{
var r = (System.Web.Routing.Route)route;
<h4>#r.Url</h4>
}

Related

route configuration subdomain

I've been trying to create a link that includes the subdomain to look like this batman.website.com, but instead it generates this website.com/?subdomain=batman
I'm generating the link through this method
#Html.RouteLink("Link", new { controller = "home", subdomain = activity.From.Username, id = activity.PostId, action = "post" })
and my routing routeconfig class looks like this
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new SubdomainRoute());
}
}
the subdomain route is heavily based off of this http://benjii.me/2015/02/subdomain-routing-in-asp-net-mvc/
Could someone point me in the right direction to format the link correctly
If you're using MVC for authentication, you could do something like this, straight into the view:
Test Link
Another way (if your authentication isn't based on MVC) would be to set the username at the View Controller on the ViewBag and then set it to display in the view:
Controller:
ViewBag.VarName = userName;
View:
Test Link
Another question that gives more detail and examples:
How to get current user, and how to use User class in MVC5?
Hopefully some of this points you in the right direction!

How to redirect custom aspx page to mvc action

I have upgrade aspx project to mvc. Now some of my old customer calling url with .aspx page and they are getting 404(not found) in mvc project.
So now I have to redirect .aspx to mvc page.
Old URL
www.domain.com/bookshop/pc-58573-53-{product_name}.aspx
New URL
www.domain.com/{product_name}
I am thinking to do via routing mechanism of mvc. like once this type of url come then it should be call my custom mvc action and in string parameter i will get pc-58573-53-{product_name}.aspx
Can you please suggest a best way to do this with minimal code.
Just define an action with route 'bookshop/{pageName}'
Here are examples for 2 scenarios using Route attribute:
In case, you don't want the URL to change:
[Route("bookshop/{pageName}")]
public ActionResult MyAction(string pageName)
{
// add logic according to what you receive in pageName property
return View();
}
or, In case you want to Redirect to a new URL:
[Route("bookshop/{pageName}")]
public ActionResult MyAction(string pageName)
{
// Create and use a method to ExtractProductNameFromPageName
string productName = ExtractProductNameFromPageName(pageName);
return Response.Redirect("~/" + productName);
}
The parameter 'pageName' here should catch the page name past 'bookshop/'.
In case, you don't have route attribute mapping enabled, add code below in RegisterRoutes method of RouteConfig.cs file:
// enable mapping of routes defined using Route attribute on specific actions.
routes.MapMvcAttributeRoutes();

Ignore first segment of url for globalization

I was required to change the way the globalisation works on my project.
Today I have
www.mysite.com.br
www.mysite.com.mx
www.mysite.com.ar
So I could access my pages like: www.mysite.com.br/default.aspx
and based on this, I make my way changing the language and the content, based on the URL
Country obj = dataContext.Country.FirstOrDefault(c => c.Domain.Equals(HttpContext.Current.Request.URL.Host.ToLower()));
But now, they said that they need it to be like this
www.mysite.com/br
www.mysite.com/mx
www.mysite.com/ar
So I need to access my pages like: www.mysite.com/br/default.aspx
I could get the Country on my function by using this
Country obj = dataContext.Country.FirstOrDefault(c => c.Abbreviation.Equals(HttpContext.Current.Request.Url.Segments.Where(s => s != "/").First()));
But when I access www.mysite.com/br/Default.aspx he gives me the error "Server Error in '/' Application The resource cannot be found". Of course, I don't have a Default.aspx inside a folder named br.
I was reading about routes. But so far I couldn't implement those and I'm not sure if this is the right path for me atm
By routes, I'm trying something like this:
Global.asax ( I had to create one, because my project didn't have one )
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{lang}/Default.aspx",
"~/Default.aspx"
);
}
But the error is the same.
I got it to work.
As it is a WebSite not a Project, I had to add RegisterRoutes(RouteTable.Routes); inside Application_Start with the help of this answer

RouteData.Values stays Empty

My Code for the Route looks like this:
RouteTable.Routes.MapPageRoute("IDP", "Person/{IDP}", "~/Person.aspx")
And now i want to get the Data on a Form, normally it works like this:
int id = Convert.ToInt32(Page.RouteData.Values["IDP"]);
But everytime i try to get the Data from the Route e.g.: http://PC-81/SkillDatenbank/Person/1
I get no Data from the Value (it is empty!)
I am using ASP.Net 4.5 with Web Forms.
Edit: I made an new Project and tested and it didnt work either
What am i Doing wrong? in the Last Project it did work like this :(
Can you help me?
Your problem ist probably located in your Routing table. I have created a WebForms project to test this out.
Open up your Global.asax (or whereever you store your RouteConfig; default is App_Start/RouteConfig.cs) and check your RegisterRoutes method. Add the following line to it, if it isn't already present.
void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
/* ... additional routes */
routes.MapPageRoute("","Person/{IDP}", "~/Person.aspx");
}
In your Application_Start there should be a line like this, if you use the default configuration with in the App_Start folder: RouteConfig.RegisterRoutes(RouteTable.Routes);
If you defined your routes in your global.asax.cs it is just RegisterRoutes(RouteTable.Routes);
If you now access your Page via http://PC-81/SkillDatenbank/Person/1 the RouteData dictionary will contain 1 set of data, like this:
Following code has worked for me, I have moved additional routes to top of the function.
Also, in my case RedirectMode is off because I'm using Jquery in my code and inorder to make a Webmethod work, I have turned off RedirectMode.
void RegisterRoutes(RouteCollection routes)
{
/* ... additional routes */
routes.MapPageRoute("","Person/{IDP}", "~/Person.aspx");
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}

Implicit connection of Action Methods with Views in ASP.NET MVC

I am currently working in a brownfield ASP.NET MVC 3 project in VS2010.
In this project, views and controllers are in separate projects. This is not something that I have seen before. In each action method there is no explicit stating of view name as below.
return View("viewName",passingModel);//projects where controllers and views are in same
I have done this implicitly in VS2012 by right clicking on the view and do add view. So I was not bothered about where is this connection between action method's return view and the view is stated.
Unlike in VS2012, in VS2010 I can not navigate to the view that is related to one particular action method by right clicking on View and doing go to view.
I tried to understand this by doing this small experiment. I created a Controller and created a Action Method call xxxx and I created a view for that implicitly as mentioned above and searched the word xxxx in entire solution but this word only appeared in controller and in the view.
So, I was unsuccessful in finding the answer. I think visual studio itself creating its own mapping to achieve this.
I would like to know who these implicit connections are created among action methods and views to understand what is going on in my project.
Edit:
Both the projects which contains controllers and views are class libraries. not asp.net mvc projects.
Global.aspx file contains this:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
DependenciesHelper.Register(new HttpContextWrapper(Context));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RoutingHelper.RegisterRoutes(RouteTable.Routes);
}
protected void Application_End()
{
//Should close the index
//If this method is not executed, the search engine will still work.
SearchService.CloseIndex();
}
The mapping is fairly straightforward. For example if you have a controller called "MyBrilliantController" and an action method called "MyExcellentAction" which returned just return View(); it would map to (in the UI project) ~/Views/MyBrilliant/MyExcellentAction.cshtml
The only time where this is different is when you are working with "Areas" - but the mapping is effectively the same, it would just consider the area folder first (ie ~/Areas/MyArea/Views/MyBrilliant/MyExcellentAction.cshtml)
Hope that helps.
EDIT - You can also specify namespaces in the global.asax file on each route for the engine to find controllers
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
new string[] {
// namespaces in which to find controllers for this route
"MySolution.MyControllersLib1.Helpers",
"MySolution.MyControllersLib2.Helpers",
"MySolution.MyControllersLib3.Helpers"
}
);
}

Categories