How to hide action and controller from url : asp.net mvc

12,664

Solution 1

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.

Solution 2

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

Share:
12,664
Suhail Mumtaz Awan
Author by

Suhail Mumtaz Awan

mail : [email protected] skype : suhail.mumtaz120

Updated on June 05, 2022

Comments

  • Suhail Mumtaz Awan
    Suhail Mumtaz Awan almost 2 years

    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.

  • Suhail Mumtaz Awan
    Suhail Mumtaz Awan almost 8 years
    Yes i already implemented that, thanks for help, +1
  • Suhail Mumtaz Awan
    Suhail Mumtaz Awan almost 8 years
    Thanks for help, but it implies on api, +1 for effort