How to hide action and controller from url : asp.net mvc [duplicate] - asp.net-mvc

This question already has answers here:
Routing in ASP.NET MVC, showing username in URL
(2 answers)
Closed 6 years ago.
Introduction
I am working on demo application where users can register.Users table have "username" field.There is "detail" action in "home" controller accepting parameter of string "username".
Code
public ActionResult Detail (string username)
{
return View();
}
Then url will be
www.example.com/home/Detail?username=someparam
Problem
Can i setup route like that ?
www.example.com/someparam
If its possible, then please let me know. Any kind of help or reference will be appreciated.
Thanks for your time.

That is doable if you change the way your routes are defined. Let's assume that you use dot net 4.5.2
Have a look in RouteConfig under App_Start.
A typical route definition is defined like this :
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Nothing stops from changing the route to look like this :
routes.MapRoute(
name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
We are basically hardcoding the controller and action to be a certain value so now you could just have url/paramname and it will hit the hardcoded combination.
This being said I would not do things like this as it's against the way MVC works
MVC routes are url/controller/action. You can skip the action for generic stuff like an Index for example and your URL becomes url/controller. MVC needs to be able to identify which controller you want to hit and which action and it's best to stay within the conventions it has.
Plus, each application will typically have more than one controller, which allows a nice Separation of Concerns. Now you've hardcoded yourself ito having just one controller and action.
What you are suggesting can be done a lot easier in a webforms manner though so maybe you want to look into that.

If you define code like this
[HttpGet, Route("api/detail/{username:string}")]
public ActionResult Detail (string username)
{
return View();
}
Then url will be
www.example.com/api/Detail/someparam
So I guest you define as following, please try with your own risk!
[HttpGet, Route("/{username:string}")]
Url will be:
www.example.com/someparam

Related

MVC Tell one view to one use controller, and another view to use another

I have an application where I don't want to use any "folders". EG
http://mydomain/Index ,
http://mydomain/Edit ,
http://mydomain/Admin ,
and so on....
I modified my defauly RouteConfig initially to look like this:
routes.MapRoute(
name: "maproute1",
url: "{action}/{id}",
defaults: new { controller = "Home", id = UrlParameter.Optional }
);
I have a Views/Home folder with all my views.
It works like a charm so whenever I enter the actionname, I don't have any issues.
If, hypothetically, I wanted to KEEP this url structure the same where I ONLY show the root domain / action-page... and I want to have SOME of these actions use one controller (HomeController.cs) and other actions (e.g. Admin) use another contoller (AdminController), is there I way I can modify my routes to say... ok.. if the action is "Admin" then use the AdminController? I have the AdminController set up with the action for "Admin" defined. I tried changing my routeconfig like this:
routes.MapRoute(
name: "maproute1",
url: "{action}/{id}",
defaults: new { controller = "Home", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "maproute2",
url: "{action}/{id}",
defaults: new { controller = "Admin", id = UrlParameter.Optional }
);
and then I set up a Views/Admin folder for the Admin view (and some other actions/views I want)
But it doesn't work. IF I have an "Admin" action in the home controller, it fires from the home controller. But I want the action to fire from the AdminController. Keep in mind I'm not just going to use ActionLinks to navigate to these pages so I can't just use an Actionlink and specify the controller. Some people are going to be going to links via a direct URL/bookmark.
If I wanted to keep my URL structure like this (http://mydomain/Action) I could just slap all my actions into ONE single controller and it would work, but I like to keep my code neat so that one controller handles functionality related to one set of models and another controller related to another set of models. For now it seems like I have to either (a) have one MASSIVE controller that is just going to get bigger and bigger or (b) I HAVE to have a more detailed path in there to have something to tell MVC what controller to use.
(BTW, I can't use querystrings... long story... don't ask)
MVC was designed to give people more control over layout from what I understand. I've been a web forms programmer for 13 years, but so far it seems that MVC has done this at the expense of giving you less control in other areas.
You may need to hardcode your Action names in your routes.
routes.MapRoute(
name: "maproute1",
url: "Home/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "maproute2",
url: "Admin/{id}",
defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
);
http://localhost/Admin should take you to the Admin/Index view and http://localhost/Home should go to Home/Index view
one simple workaround is to create an admn action in home controller and then redirect from there to Admin controller but i am not sure you want to do ths as it may hit performence
public ActionResult Admin()
{
return Redirect("Admin/Index");
}
i would say try something other if you can and even then if you cant find a way out use this workaround

How do I do Short URLs in MVC?

Suppose I want to publish (like in paper catalogs) some "short URLs" that are easy to type/remember, but I want them to redirect to a verbose, SEO-friendly URL. How do I accomplish that with MVC routes?
Example:
http://mysite.com/disney
becomes
http://mysite.com/travel/planning-your-disney-vacation (with "travel" as the Controller)
The things I've tried:
Just setup a route for it. Problem: the URL doesn't change in the browser (it stays "/disney".
Use NuGet package RouteMagic (see Haacked's article). Problem: I get an error: The RouteData must contain an item named 'controller' with a non-empty string value. I think this is because I don't have a static word before my controller ("travel") like he did (with "foo" and "bar")???
Use a redirect module (like Ian Mercer's). Problem: the route matches on my HTML.ActionLinks when creating URLs which I don't want (Haacked mentions this in his article and says that's why he has GetVirtualPath return NULL ...?)
I'm out of ideas, so any would be appreciated!
Thanks!
You could set up a catch-all type route, to direct all /something requests to a specific action and controller, something like:
routes.MapRoute(
"ShortUrls",
"{name}",
new {controller = "ShortUrl", action = "Index", name = UrlParameter.Optional}
);
(depending on how the rest of your routing is set up, you probably don't want to do it exactly like this as it will likely cause you some serious routing headaches - but this works here for the sake of simplicity)
Then just have your action redirect to the desired URL, based on the specified value:
public class ShortUrlController : Controller
{
//
// GET: /ShortUrl/
public ActionResult Index(string name)
{
var urls = new Dictionary<string, string>();
urls.Add("disney", "http://mysite.com/travel/planning-your-disney-vacation");
urls.Add("scuba", "http://mysite.com/travel/planning-your-scuba-vacation");
return Redirect(urls[name]);
}
}
I just faced the same problem.
In my Global:
routes.MapRoute(
"ShortUrls",
"{name}",
new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
In my Home Controller:
public ActionResult Index(string name)
{
return View(name);
}
This way is dynamic, didn't want to have to recompile every time I needed to add a new page.
To shorten a URL you should use URL rewriting technique.
Some tutorials on subject:
url-rewriting-with-urlrewriternet
url-routing-with-asp-net-4
URL rewriting in .Net

How do I create a simple route in MVC3?

I am writing a short url service in MVC3, partly as a learning tool.
When I load the url http://mysite/abc I want to redirect to an action in my controller with the following signature:
public ActionResult RedirectToLink(string shortLink)
How would I create a route in order to run this code? I have tried the following:
routes.MapRoute("Link", "{shortLink}", new { controller = "LinkController", action = "RedirectToLink" });
Alternatively, if someone can point me towards a decent primer for MVC3 that actually covers the basics rather than what's changed since the last version and would cover this scenario, I'd be much obliged.
Thanks
this is the route your want :
routes.MapRoute(
"ShortLink", // Route name
"{shortLink}", // URL with parameters
new { controller = "Link", // Parameter defaults
action = "RedirectToLink",
shortLink= UrlParameter.Optional }
);

404 asp.net mvc - beginner question in routing

This is a beginner level question for asp.net MVC
I have the following code in global.asax.cs
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 = (string)null } // Parameter defaults
);
}
in Homecontroller.cs i have updated the Index method as follows
public ActionResult Index(string id)
{
ViewData["Message"] = "Welcome to ASP.NET MVC1!"+ id;
return View();
}
My understanding is, if I give the url http://localhost/mvc1/default/1 it should work
instead it is throwing up 404 error
any help what is the reason behind this
I'm assuming your application is called "mvc1" and that's the root of your project. If that's the case:
So "default" is the name if your route, not the name of the action. Basically what the routing engine does is look for a controller and action that matches requests coming in. Given the route you have setup, it would break down like this:
http://localhost/MVCApplication1/default/1
(cont) (action)
If certain parts of the route are omitted, it will attempt to fill in the missing values with the defaults you have specified. As you can see, there is no controller named DefaultController in your project, and thus it uses the default you've specified which is Home. It then tries to find an action method called default and fails again, so it uses the default value in your route, which is Index. Finally, you have 2 segments left in your URL, and no route matches that pattern (2 segments after the action), so it can't find the right place to go.
What you need to do is remove one of your segments, and this should work. Routing can be a little tricky, so I would recommend reading up on it.
The URL you're requesting is asking for a controller called "mvc1" and an action called "default" which will receive an id of "1". Since you don't have a controller named "mvc1" (I assume?), you're getting the 404 error.
The defaults for controller and action are only used if controller and action aren't provided. Since you provided controller and action, MVC is looking for them specifically.

Vanity MVC Routes?

I want to have a route that looks something like: www.abc.com/companyName/Controller/Action/Id
However, all the company names need to map to the same "base" controllers, regardles of what the name is. I only need the companyName for authentication purposes.
Also, if there's no companyName provided, I need to map to a different set of controllers altogether.
How do I do this? I'd also appreciate a good routing resource so I don't have to ask questions like this.
routes.MapRoute(
"CompanyRoute",
"{companyName}/{controller}/{action}/{id}",
new { controller = "MyBaseCompanyController", action = "Index", id = "" }
);
routes.MapRoute(
"NoCompanyRoute",
"{controller}/{action}/{id}",
new {controller = "DifferentDefaultController", action = "Index", id = "" });
Routing is quite a complex topic, but it's covered well in Professional ASP.Net MVC 1.0. For online resources, I would suggest starting here, and then coming back to Stack Overflow ;)
In case if you wish to Resolve the errors caused due to routing . i suggest the following tool , which i found to be extremely useful.
Route Debugger
Go to Global.asax.cs, and add the following route in the RegisterRoutes() method before the "Default" route:
routes.MapRoute(
"Vanity", // Route name
"{company}/{controller}/{action}/{id}", // URL with parameters
new { company = "", controller = "Home", action = "Index", id = "" } // Parameter defaults
);

Resources