Custom url for different ActionResults? - c#

I am in the process of moving old website to a new ASP .Net MVC website. The old site has pretty bad url naming scheme. I would love to ignore the old ways and just create new urls, however, A LOT of links point to the old links for SEO. Therefore, I have to maintain the older url.
So let's say this is the old url:
web.com/items/products/Hello-World-Hyphens
How do I input that on MVC?
I got ProductsController:
ActionResult HelloWorldHyphens() { return View(); }
Which will output to web.com/products/HelloWorldHyphens
However, I need it written in the old ways. Starting with /items/ and having hyphens in controller name.
Is there a way I can do something like this?
[OutputUrl="/items/products/Hello-World-Hyphens"]
ActionResult HelloWorldHyphens()

As you are moving to a new ASP MVC website then you can take advantage of attribute routing in MVC 5.
If you add attribute routing when you register your routes:
routes.MapMvcAttributeRoutes();
Then you can add routes on methods:
[Route("/items/products/Hello-World-Hyphens")]
ActionResult HelloWorldHyphens()

Related

.net-core WebApp Dynamic Route to Controller

I'm trying to migrate an existing asp.net website to dotnet-core (version: 1.0.3), and have some trouble with the routing of the requests.
The old Structure was: web.site.com/[categorie]/{id?}
Now with the new envoirment it should be the same, but i cant get it work.
Since the [categorie] field comes out of the Database, and the position in dotnet-core is usualy the controller.
If this would be static i could proberly just define x Routes, but this can be changed on the fly.
So i need a hint or maybe a Solution how to route a dynamic set of [categorie] to the same Controller.
Cheers Isparia

MVC core routing not functioning as expected

So it's my first time setting up an netcore MVC based application. I've used MVC 4 in the past on plain old asp.net.
So i'm having issues with my routing. My application is an single page application (spa) that is accessible from the home controller on the index action. I can access this controller method fine, and my defaults are set so that this is navigated to at route: /.
I also have a second controller for authentication called AccountController. This controller's methods take and return JSON, rather then views. I can also access the methods on this controller from my application.
The issue i'm having lies in my next controller, which is the start of my API.
As such, i've put it in a folder called api inside my controllers folder. However, no matter what i try, i cannot seem to get the methods on the controller accessible. I have also tried moving it out of the api folder and just having in the route of the controllers folder.
The routing deffinition
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller=Core}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I've tried adding and removing the api definition, removing the api part, and adding a template for actions aswel, all to no effect.
The troublesome controller
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I've tried adding [Route(~routing here~)] annotations to this controller and its methods with no success either.
Folder structure
I should also mention that i've tried plenty of URL's to access this controller on:
/api/Core/
/Core/
/api/Core/Get
I've been wracking my brain for the best part of a day trying to get this sorted and i know i'm missing something obvious, i just can't for the life of me work out what it is.
Edit:
I've added a cut-down sample of my project to github at: https://github.com/lexwebb/aspnet-test if anyone would like a complete example
Edit 2
It appears that my example works, i'm going to add things in to see what breaks it
AFAIK, default route requires the {action} using as well.
Instead of "api" default routing, you may to use the following configuration for such type of controllers (RESTFul controller):
[Route("api/[controller]")]
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I found this Routing is ASP.NET Core article useful in the past.
So as it turns out, i had made a mistake in a totally unrelated place. I had renamed my project half way through the beginning stage of development, after i had build scripts in place. This led to the the wrong dll being referenced on the server when the code was ran, a version that had all of my routing EXCEPT the new one, of course.

Getting canonical url based on route data from outside MVC project

I have a MVC4 project and I have an external project that sends emails out that refer to areas of the site.
Rather than hardcoding urls into the emails I want to be able to make sure that I get the canonical url from the routing. I can reference the MVC project which means I believe I should be able to get any compile time information that it has (which includes routes and things).
I have managed to create a RouteCollection and fill it with my routes but I am now struggling with how I can query this collection. The only way I have found is the RouteUrl method on UrlHelper but this needs a UrlHelper with the appropriate routing data which I am having trouble creating. I also would hope that there would be better methods available to query a routecollection.
Essentially I have this route:
routes.MapRoute
(
"ShowBlog",
"blog/{shortcode}/{slug}",
new { controller = "Blog", action = "ShowBlog", shortcode = "", slug = "" }
);
And I want some code like GetUrl("ShowBlog", new {shortcode = "foo", slug="bar"}) that will return blog/foo/bar.
So how can I do this?
If you can wire up a UrlHelper from a test project, you can do it from any other external project. However you need to register the routes in the external project just like you do during Application_Start in the MVC project.
You will also need to mock up an HttpContextBase and a RequestContext, which means your external project will at least need to know the application path where your MVC project is installed. This would be easier if your external project could use a mocking library just like a test project would. Is that a possibility, or not?
If so, here is a link for how to do it with Moq. You don't need the controller, but you can use similar code for your HttpContext, RequestContext, and UrlHelper.

mapRoute to a Web Form using ASP.NET 4

I have a Url like this
http://localhost:4737/Site/listing/NH/Plaistow/2831516
and I want it to reroute to
http://localhost:4737/Site/listing.aspx
I was reading how to do this for Web Forms here
https://web.archive.org/web/20211020111718/https://www.4guysfromrolla.com/articles/012710-1.aspx
Here's what my route looks like.
routes.MapRoute(
"FriendlyUrl",
"Site/listing/{state}/{town}/{mlsnumber}",
"~/Site/listing.aspx");
In my listing page I plan on accessing the following variables
Page.RouteData.Values["state"]
Page.RouteData.Values["town"]
Page.RouteData.Values["mlsnumber"]
But when I navigate to http://localhost:4737/Site/listing/NH/Plaistow/2831516,
I just get a HTTP 404 error.
I know how to get this working with MVC, but this is a fairly large application, all written with web forms, so rewriting isn't feasible.
Any ideas on how to troubleshoot this would be helpful.
Thanks !
Here is the working code. Thank you to mrchief for helping me resolve this.
routes.MapPageRoute(
"FriendlyUrl",
"listing/{state}/{town}/{mlsnumber}",
"~/listing.aspx");
Yore doing it the other way. If you're using WebForms, you need to implement UrlRoutingModule as shown here: https://web.archive.org/web/20201205221404/https://www.4guysfromrolla.com/articles/051309-1.aspx
The Routing Rules were designed for use in ASP.Net MVC applications where you redirect a Url to its appropriate Controller (Page in WebForms) with action params (query params in WebFroms parlance).

What string does come to ASP.NET MVC route?

What string does come to ASP.NET MVC route if I request http://subdomain.domain.com/pathAndQuery?
Is route applied to the whole string or to pathAnQuery part only?
Routes are applied just to the pathAndQuery.
This is why your routes work on your development and production sites despite the fact that they have different URLs.

Categories