ASP.Net MVC 2 Routing - asp.net

I need a feedback on a routing-related issue I've found while publishing an ASP.NET MVC 2 application.
In the global.asax file I defined the following routes:
// Thumbnails routing.
// Sample URL: resizer/resizeImage/200/200/Error/error.jpg
routes.MapRoute("Resizer","Resizer/{action}/{width}/{height}/{folder}/{file}",
new { controller = "Resizer", action = "ResizeImage", width = 100,height = 100,
folder = "Error", file = "error.jpg"
}
);
// Default routing.
// Sample URL: /Home/Index
routes.MapRoute("Default", "{controller}/{action}.aspx/{id}",
new { controller = "Home", action = "Index", id = (string)null }
);
So, firstly I had to add .aspx for the default routing otherwise the hosting server (Aruba) does not perform properly routing... so first question: is there any other workaround to maintain normal routing (i.e. without adding .aspx)?
The 'Resizer' route should allow to call a controller that should generate thumbnails images: It works locally but not when the web site is published.
It seems that the route like 'resizer/resizeImage/200/200/Error/error.jpg' is not recognized.
How can I handle this issue?

thanks for your reply.
I modified the routing adding '.aspx' to {action} also in the Resizer route.
Now it looks like:
routes.MapRoute("Resizer",
"Resizer/{action}.aspx/{width}/{height}/{folder}/{file}",
new { controller = "Resizer", action = "ResizeImage",
width = 100, height = 100, folder = "Error", file = "error" });
It seems to work properly, it is actually the only way to activate IIS routing.
I also deleted the file extension (.jpg), just to avoid problem with the Dot character.
Marco

I don't think there is another way to avoid the .aspx instead the "normal" routing.
Any how I don't think it's a big deal.
I also think that in the code that you posted (I didn't try it) the routing is not correct: to add the aspx you should put the aspx after the controller name, in the default like in the resizer one.
Something like that:
routes.MapRoute("Resizer",
"Resizer.aspx/{action}/{width}/{height}/{folder}/{file}",
new { controller = "Resizer", action = "ResizeImage",
width = 100, height = 100, folder = "Error", file = "error.jpg" });
/Stefano

Related

Wrong URI after Form Submit MVC 3 asp.NET

I'm a little confused on something here. I have a form, and the URL for that form is:
http://domain.com/Home/requestquote
When I click submit on a form and the method handling this form located in the form controller sends back a view, the URI looks like this:
http://domain.com/form/requestQuoteSubmit where requestQuoteSubmit is the method.
This occurs both when validation sends the page back for errors and when there is a successful form submit.
On success the view being sent back is Home/thanks and on error it should just send back Home/requestquote. Everything seems to work fine except for the fact that the URI is not what it is supposed to be. This causes everything else on the page to break because my links look like this:
#Url.RouteUrl(Model.CompanyPageDatabaseModel.companyCode, new { Controller = MVC.services.Name, Action = MVC.services.ActionNames.page })
So that companyCode value isn't being passed around properly and forming the links correctly. I'm not sure how or why the form method is sending back the correct page, but setting the URI to itself?
Here are my routes.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
null,
"{action}",
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index },
new { RootAction = new RootActionConstraint() } // Route Constraint
);
routes.MapRoute(
null, // Route name
"{controller}/{action}", // URL with parameters
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index }, // Parameter defaults
new { controller = "Home|contact|franchise|form|resources|services|technology|community|careers|carriers|about" }
);
routes.MapRoute(
null,
"{companyCode}/{action}",
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index },
new { RootAction = new RootActionConstraint() } // Route Constraint
);
routes.MapRoute(
"jax",
"{companyCode}/{controller}/{action}",
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index }
);
The last route value is an example of a franchisee route.
Also here is the form code in the view:
#using (Html.BeginForm("requestquote", "form", FormMethod.Post))
{ }
Any ideas?
Thanks.
Edit: Added in my routes.
There is a concept referred to as PRG, which stands for Post-Redirect-Get.
The basic idea is that you Post the form to your application. After processing the input, you then Redirect to a Get request at the correct URL, instead of serving the user a content response directly from the submission.
This is good for many reasons, but the underlying one is separation of concerns. (When you don't separate concerns weird stuff like all the links might breaking on your page tends to happen...)
So, the solution for you is to process the submission, and if invalid, store your Validation content in TempData and return a RedirectToRouteResult(controller:"Home",action:"RequestQuote")
Update: I found the original article I read to learn this concept. It's in terms of the original ASP.NET MVC release, but it should be mostly the same. Check out http://www.eworldui.net/blog/post/2008/05/ASPNET-MVC---Using-Post2c-Redirect2c-Get-Pattern.aspx

RESTful ASP.NET MVC3 Routing

I've looked through the various questions already asked on this topic, and I've spent time trying to get it working how I would like it to, but I haven't had much luck so hopefully someone here can help me fill in the gaps.
With a new site I'm creating I wanted to try getting the URL structure to be more RESTful (I wanted to do it with my first MVC3 creations, but, time did not permit such experimenting). However, I don't want the different URLs to all point to the same action. I want different actions for each resource requested to keep the controller code concise and intuitive.
Here is an example of the URL structure I'm shooting for:
/Case //This currently works
/Case/123 //This currently works
/Case/123/Comment //This one does not work (404)
Here is how I currently have my routes setup:
routes.MapRoute(
"Case",
"Case/{id}",
new { controller = "Case", action = "Number" }
);
routes.MapRoute(
"CaseComment",
"Case/{caseId}/Comment/{id}",
new { controller = "Case", action = "CaseComment" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The first two URL's I listed are worked correctly with this route structure. The first URL takes me to my listing page. When an id is specified, I hit the Number action so I can show details for that particular record. The Comment URL is not working.
I have the action for the third URL defined as:
public ActionResult CaseComment(string caseId, string id) {
//Narr
}
What am I missing? And, could I set this up in an easier fashion for future resources?
I believe MapRoutes are order specfic, so
/Case/123/Comment
is using your
routes.MapRoute(
"Case",
"Case/{id}",
new { controller = "Case", action = "Number" });
route, thus throwing a 404. Most specific route should be place above more general routes.
Try placing the CaseComment route above the Case route.
Mapping routes are order specific.
One thing you may wish to consider for restful routing in MVC is a project called RestfulRouting that is on GitHub originally written by Steve Hodgekiss.
https://github.com/stevehodgkiss/restful-routing
If nothing else, looking at the code may well help you.
Hope this helps.
I needed to make the id parameter optional.
routes.MapRoute(
"Case Resources",
"Case/{caseId}/{action}/{id}",
new { controller = "Case", action = "CaseComment", id = UrlParameter.Optional }
);

ASP.Net MVC 2 Area, SubArea and Routes

I have been looking around for a solution for my problem. Found alot of similar issues, but none of them led to a solution for me.
I am trying to register an Area within an Area. This works however it "partially" screws up my routing.
My route registrations in the order they are registered, consider the FooBar and Foo registrations to be coming from AreaRegistrations
routes.MapRoute("FooBar_default",
"Foo/Bar/{controller}/{action}",
new { area = "Foo/Bar", controller = "Home", action = "Index"},
new[] { BarHomeControllerType.Namespace }
);
routes.MapRoute("Foo_default",
"Foo/{controller}/{action}/{id}",
new { area = "Foo", controller = "Start", action = "Index", id = UrlParameter.Optional },
new { controller = new NotSubArea()},
new[] { typeof(StartController).Namespace }
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("PagesRoute", "Pages/{action}", new { controller = "Pages", Action "Index" }).DataTokens["UseNamespaceFallback"] = false;
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { typeof(HomeController).Namespace }
).DataTokens["UseNamespaceFallback"] = false;
Now the following problem occurs. When going to Website/Foo/ or Website/Foo/Bar links in those pages are generated correctly using:
!{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = "Foo/Bar"})}
or
!{ Url.Action("Index", "Home", new { area = "Foo/Bar"}) } //or a different area
However when i use this in my main pages, in other words Website/ or Website/Home etc..
!{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = ""})}
or
!{ Url.Action("Index", "Home", new { area = ""}) }
//or with no area identifier specified
It generates the Url: Website/Foo/Bar/Home etc... Which ofcourse is wrong.
When i remove the Area registration for Foo/Bar it all works again. Going to the urls Website/Home/About or Website/Home directly does display the right pages, so im guessing somehow the internal UrlHelper is picking the wrong routes to render.
I tried switching the order of the FooBar_default and Foo_Default routes, so that the Foo_default route is registered before the FooBar_default route, but then the area does not work anymore (resource not found) and the links are still generated incorrectly.
What i find most odd is that removing the Foo/Bar registration solves the problem. I was hoping someone could shed some insight on this matter..
What you need to understand that an Area is just a routing concept which Microsoft have neatly wrapped up the concept or UrlRouting to get people started.
You can actually get the MVC framework to route your request however you like according to your requirements.
What you might need to look at doing, is writing your own RouteHandler. This will enable you to correctly direct how the MVC framework routes any request accoring to your requirements.
See this answer to asp.net mvc complex routing for tree path as an example to get you started.
chris166 outlines that my implementing your own IRouteHandler, and mapping your route to use that instead should get you what you need. Its a bit more effort than using out the box solution of areas, but should get you better results.
routes.MapRoute(
"Tree",
"Tree/{*path}",
new { controller = "Tree", action = "Index" })
.RouteHandler = new TreeRouteHandler();

Default value for parameter in Controller Method is overriding everything

Hello i have just started learning mvc2 and im having a problem with the default value for the parameter page(you can see the method below).
Its always 0 regardless of what i type in the URL. For example this
h.ttp://localhost:52634/Products/List/2
should show page 2 but when in debug mode the page parameter is 0, so im always getting the first page of the list in my view.
i am using the predefined standard routes in global asax when you start a new mvc2 project.
am i missing something?
//This is the ProductsController
public ViewResult List(int page = 0)
{
var products = productsRepo.Products()
//send in source, current page and page size
productList = new PagedList<Product>(products, page, 10);
return View(productList);
}
It's a routing issue, the default route specifies an id property, you're using a property called page. I'm new to MVC myself, but add this route before the default route:
routes.MapRoute("MyRoute", "{controller}/{action}/{page}",
new { controller = "Foo", action = "List", page = UrlParameter.Optional });
Remove the " = 0", and do:
public ViewResult List(int? page)
{
int val = page.GetValueOrDefault(0);
And use val everywhere instead of page. That should work. If not, it's an issue with routing.
HTH.
I know it's very late to answer. As default route for MVC is following
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
which is expecting that parameter name should be id. Now you have 2 options here either change your parameter name to id or the other option is define your own route in route.config file which is under App_Start folder.

Creating a URL in the controller .NET MVC

I need to be able to construct a link in the Action on the controller to send an email. What is best practice to do this? I don't want to construct it myself in case my routes change.
Should I have a view for each email and render that and send it? That might be a good way of doing it.
If you just want to get the path to a certain action, use UrlHelper:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper:
string url = this.Url.Action("About", "Home", null);
If you need the full url (for instance to send by email) consider using one of the following built-in methods:
With this you create the route to use to build the url:
Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Here the url is built after the route engine determine the correct one:
Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
In both methods, the last 2 parameters specifies the protocol and hostname.
Regards.
I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.
My solution looks like this:
string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.
EDIT: I found this useful as well.
Another way to create an absolute URL to an action:
var relativeUrl = Url.Action("MyAction"); //..or one of the other .Action() overloads
var currentUrl = Request.Url;
var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url property if you inherit from Controller.

Resources