ASPMvc Routing Issues with legacy url - asp.net-mvc

I have got a legacy url that I cannot change, which is output on a page which needs to now post to a new MVC version of the page:
http://somesite.com/somepage?some-guid=xxxx-xxxx
Now I am trying to map this to a new controller but I need to get the some-guid into my controller:
public class MyController : Controller
{
[HttpGet]
public ActionResult DisplaySomething(Guid myGuid)
{
var someResult = DoSomethingWithAGuid(myGuid);
...
}
}
I can change the controller and routes as much as I like, however the legacy url cannot change. So I am a bit stumped as to how I can get access to the some-guid.
I have tried routing with the ?some-guid={myGuid} but the routing doesn't like the ?, so then I tried to let it autobind, but as it contains hyphens it doesn't seem to bind. I was wondering if there was any type of attribute I could use to hint that it should bind from a part of the querystring...
Any help would be great...

I would have thought you would have done a route a bit like this..
routes.MapRoute(
"RouteName", // Name the route
"somepage/{some-guid}", // the Url
new { controller = "MyController", action = "DisplaySomething", some-guid = UrlParameter.Optional }
);
The {some-guid} part of URL matches your url parmater and passes it to the controller.
So if you have your action like so :
public ActionResult DisplaySomething(Guid some-guid)
{
var someResult = DoSomethingWithAGuid(some-guid);
...
}
Give that a go and see how you get on..

routes.MapRoute(
"Somepage", // Route name
"simepage", // URL with parameters
new { controller = "MyController", action = "DisplaySomething"
);
And then in your controller:
public class MyController : Controller {
public ActionResult DisplaySomething(Guid myGuid)
{
var someResult = DoSomethingWithAGuid(myGuid);
...
}
}

Try this:
routes.MapRoute("SomePageRoute","Somepage",
new { controller = "MyController", action = "DisplaySomething" });
And then in your controller:
public ActionResult DisplaySomething() {
Guid sGuid = new Guid(Request.QueryString["some-guid"].ToString());
}

Related

How to utilize a user-defined url action in asp,net mvc?

My hope is to provide a method to end users that will let them enter a value 'SmallBuildingCompany', and then use this value to make a custom url that will redirect to an informational view. so for example, www.app.com/SmallBuildingCompany. Can anyone point me to some information to help on this?
edited 161024
My attempt so far:
I added this within RouteConfig.
RouteTable.Routes.MapRoute(
"Organization",
"O/{uniqueCompanyName}",
new { controller = "Organization", action = "Info" }
and added a new controller method and view under the organization controller.
public async Task<ActionResult> Info(string uniqueCompanyName)
{
var Org = db.Organizations.Where(u => u.uniqueCompanyName == uniqueCompanyName).FirstOrDefault();
Organization organization = await db.Organizations.FindAsync(Org.OrgId);
return View("Info");
}
You can achieve this by using the SmallBuildingCompany part of the URL as a parameter for an action that is used to display every informational view.
Set up the Route in Global.asax.cs to extract the company name as parameter and pass it to the Index action of CompanyInfoController:
protected void Application_Start() {
// Sample URL: /SmallBuildingCompany
RouteTable.Routes.MapRoute(
"CompanyInfo",
"{uniqueCompanyName}",
new { controller = "CompanyInfo", action = "Index" }
);
}
Note that this Route will probably break the default route ({controller}/{action}/{id}), so maybe you want to prefix your "Info" route:
protected void Application_Start() {
// Sample URL: Info/SmallBuildingCompany
RouteTable.Routes.MapRoute(
"CompanyInfo",
"Info/{uniqueCompanyName}",
new { controller = "CompanyInfo", action = "Index" }
);
}
Then the CompanyInfoController Index action can use the uniqueCompanyName parameter to retrieve the infos from the database.
public ActionResult Index(string uniqueCompanyName) {
var company = dbContext.Companies.Single(c => c.UniqueName == uniqueCompanyName);
var infoViewModel = new CompanyInfoViewModel {
UniqueName = company.UniqueName
}
return View("Index", infoViewModel);
}
ASP.NET Routing

Redirect with ASP.NET MVC MapRoute

On my site, I have moved some images from one folder to another.
Now, when I receive a request for old images '/old_folder/images/*' I want to make a permanent redirect to new folder with these images '/new_folder/images/*'
For example:
/old_folder/images/image1.png => /new_folder/images/image1.png
/old_folder/images/image2.jpg => /new_folder/images/image2.jpg
I have added a simple redirect controller
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent(path);
}
}
Now I need to setup proper routing, but I don't know how to pass the path part to the path parameter.
routes.MapRoute("ImagesFix", "/old_folder/images/{*pathInfo}", new { controller = "Redirect", action = "Index", path="/upload/images/????" });
Thanks
I would do in next way
routes.MapRoute("ImagesFix", "/old_folder/images/{path}", new { controller = "Redirect", action = "Index" });
and in controller like that
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent("/upload/images/" + path);
}
}
first download and install RouteMagic package from this link , then redirect your old address to the new address Like the below code :
var NewPath = routes.MapRoute("new", "new_folder/images/{controller}/{action}");
var OldPath = routes.MapRoute("new", "old_folder/images/{controller}/{action}");
routes.Redirect(OldPath ).To(NewPath );
for more information please check out the following link
Redirecting Routes To Maintain Persistent URLs
Answer above using RouteMagic is a good idea, but the example code is wrong (it's included in Phil's post as a bad example).
From the RouteMagic Github demo site global.asax.cs:
// Redirect From Old Route to New route
var targetRoute = routes.Map("target", "yo/{id}/{action}", new { controller = "Home" });
routes.Redirect(r => r.MapRoute("legacy", "foo/{id}/baz/{action}")).To(targetRoute, new { id = "123", action = "index" });
If you specify two routes, you will be setting up an extra mapping that will catch URLs which you don't want.

Url.RouteUrl not gettting an API route in MVC5

I created a MVC 5 site using its template and added the following API controller:
namespace MvcSite.Controllers {
public class TestController : ApiController {
[Route("test/send"), HttpGet]
public String Send() {
return "SENT";
}
} // TestController
} // MvcSite.Controllers
When I access "/test/send" I get the string "SENT" back as expected ...
In a Razor view or in a Controller I need to get the URL of the send action so I tried:
var url = Url.RouteUrl(new { controller = "Test", action = "Send", HttpRoute = true });
But url is null ... I have no idea why ...
The API route is working fine so it is in the Route Table ...
What am I missing?
Thank You,
Miguel
Configure a named route and use the HttpRouteUrl method to get the URL.
[Route("test/send", Name = "Send"), HttpGet]
public String Send() {
return "SENT";
}
Get the URL like this:
var url = Url.HttpRouteUrl("Send", new {});

Change URL to remove query string variable name

I have an MVC application and the url looks like this;
/celebritypage/celebrityname=Elma Fudd
What I'd like is to only have;
/celebritypage/Elma Fudd
Is this possible within routing?
Sure, something like this should work:
routes.MapRoute(
"RouteName",
"celebritypage/{name}",
new { controller = "celebritypage", action = "celebrityname" }
);
Then make sure your controller action is ready for the parameter:
//inside celebritypage Controller
public ActionResult celebrityname(string name) {
//code
return View("ViewName");
}

ASP.NET MVC Areas in Individual Projects - Refactor AreaRegistration Stuff

I'm trying to molularize my ASP.NET MVC application by moving each Area into their own project. Everything was working fine until i decided to refactor out the AreaRegistration stuff and use my own approach (This way i can also register filters and dependencies within my module). Using reflector i have managed to come up with the following.
First i implement the following interface for each module/area:
public interface IModule {
string ModuleName { get; }
void Initialize(RouteCollection routes);
}
E.g.:
public class BlogsModule : IModule {
public string ModuleName { get { return "Blogs"; } }
public void Initialize(RouteCollection routes) {
routes.MapRoute(
"Blogs_Default",
"Blogs/{controller}/{action}/{id}",
new { area = ModuleName, controller = "Home", action = "Index",
id = UrlParameter.Optional },
new string[] { "Modules.Blogs.Controllers" }
);
}
}
Then in my Global.asax file (Application_Start event) i say:
// Loop over the modules
foreach (var file in Directory.GetFiles(Server.MapPath("~/bin"), "Modules.*.dll")) {
foreach (var type in Assembly.LoadFrom(file).GetExportedTypes()) {
if (typeof(IModule).IsAssignableFrom(type)) {
var module = (IModule)Activator.CreateInstance(type);
module.Initialize(RouteTable.Routes);
}
}
}
I then removed the existing AreaRegistration stuff. Everything is working fine up to this point. When i run my application and render the link to a module, e.g.:
#Html.ActionLink("Blogs", "Index", "Home", new { area = "Blogs" }, null)
The correct url is displayed but when i click on the url it displays the wrong view. After debugging it looks like the url is routed to the correct Action within the HomeController of my Blogs module. However it tries to display the Home/Index.cshtml view in the main project and not the one in the module/area. I'm guessing somewhere along the lines i have missed how to tell the view engine to treat the routed url as an area as it seems to be ignoring the AreaViewLocationFormats (inside the RazorViewEngine).
I'd appreciate it if someone could show me what i'm missing. Thanks
After further refactoring it appears that, the view engine looks for an area data token. I therefore changed the code to add routes in Initialize method of the module as:
// Create the route
var route = new Route("Blogs/{controller}/{action}/{id}", new RouteValueDictionary(new { area = ModuleName, controller = "Home", action = "Index", id = UrlParameter.Optional }), new MvcRouteHandler());
// Add the data tokens
route.DataTokens = new RouteValueDictionary();
route.DataTokens["area"] = this.ModuleName;
route.DataTokens["UseNamespaceFallback"] = false;
route.DataTokens["Namespaces"] = new string[] { "Modules.Blogs.Controllers" };
// Add the route
routes.Add(route);
Hope this helps.

Resources