How to add custom url while using friendly urls

Mohamed Saad 20 Reputation points
I Need your Help Please; I'm developing a web application using c# I used Microsoft AspNet FriendlyUrls to make url without the suffix aspx in App_Code>App_start I added the following class

public static class RouteConfig
    public static void RegisterRoutes(RouteCollection routes)
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings,new WebMethodFriendlyUrlResolver());

    public class WebMethodFriendlyUrlResolver : WebFormsFriendlyUrlResolver
        public override string ConvertToFriendlyUrl(string path)
            if (HttpContext.Current.Request.PathInfo != string.Empty)
                return path;
                return base.ConvertToFriendlyUrl(path);
in Global.asax i used the following code

void Application_Start(object sender, EventArgs e)
        // Code that runs on application startup

it's working fine for dropping aspx part from url NOW.......... I have a search page uses 3 parameters in url , as a example (Plumber,Cairo,Dar Elsalam)

How to make Up URL become

I Would be appreciated to Your ideas

i searched over internet for a solution but couldn't find a suitable solution to my case

I tried this code

routes.MapPageRoute("plum-darelsalam", "plumber-in-dar-elsalam", "~/find?Syx=job=Plumber%20+%20state=CAIRO%20+%20city=ELSALAM%20DAR%20+%20.aspx");

routes.EnableFriendlyUrls(settings,new WebMethodFriendlyUrlResolver());
But didn’t work ☹️
A set of technologies in the .NET Framework for building web applications and XML web services.
3,364 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,483 questions
{count} votes

Accepted answer
  1. Albert Kallal 5,146 Reputation points

    Hum, it not clear why people are suggesting re-write rules and all kinds of mumbo-jumbo?

    Friendly URL's once turned on "just work". And they are one of my "favorite" features in

    Friendly URL's simple allow you to take a "messy" and rather unfriendly URL, and present the "url" parameter's in a nice clean, easy to read URL. In fact, your users will see and think of the URL as a folder like path name.

    Want to see a example of friendly URL's in action? Why of course just look at this page we are all reading!!!

    So, say I have a page called Hotels. (to display some hotels).

    I could use this messay (and unfriendly URL) to say display hotels from a given city.


    And of course with 2 or 3 parameter's, the URL becomes not only hard to read, but ALSO very difficult for users to change or modify, or use.

    With a Friendly URL, the above then becomes this:


    So, the above kind of looks like a folder path. Users can not only share that link, but so nice and clean is that link, that they will often then use such a format to their advantage, and then might type in this for hotels in another city:

    Hotels/City/New York

    Is that not oh so nice?

    So, friendly URL's once turned on? The open up all kinds of REALLY nice URL's for you to use, and VERY little code is required to use them. And no, you don't start making or writing re-write rules.

    So, say I wanted to show invoices for hotels, I could then have this:

    Hotels/City/Invoices/New York

    or even say this:


    All, I repeat all of the above examples don't require ANY re-write rules. You ONLY require that friendly url's be truned on.

    so, then how do we use friendly URL's ?

    Well, from a code point of view, any additonal "/" and values beyond the aspx page in question can be simple used in code behind (the values are retutrned as a "list" of strings.

    So, lets do the Hotels and city example.

    So a simple Gridview control can be dropped into the web page. Say this:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="ID"  width="40%"   GridLines="None"
            CssClass="table"  >
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName" HeaderText="LastName"  />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"  />
                <asp:BoundField DataField="Description" HeaderText="Description"  />
                <asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign="Center">
                        <asp:CheckBox ID="chkActive" runat="server" 
                            Checked='<%# Eval("Active") %>'/>
                        <asp:Button ID="cmdView" runat="server" Text="View" 
                            OnClick="cmdView_Click" Height="32px" CssClass="btn" />

    Now, our "non" friendly URL is Hotels.aspx. but, we enable friendly URL's, and say we type in this:


    The code behind for the Hotels.aspx page would/could then be this:

            protected void Page_Load(object sender, EventArgs e)
                if (!IsPostBack)
                    string strSQL = "SELECT * FROM tblHotelsA";
                    SqlCommand cmdSQL = new SqlCommand(strSQL); 
                    IList<string> fURL = new List<string>();
                    fURL = Request.GetFriendlyUrlSegments();
                    if ( (fURL.Count == 2) && (fURL[0] == "City") )
                        // user entered City
                        cmdSQL.CommandText += " WHERE City = @City";
                        cmdSQL.Parameters.Add("@City",SqlDbType.NVarChar).Value = fURL[1];
                    cmdSQL.CommandText += " ORDER BY HotelName";
                    GridView1.DataSource = General.MyRstP(cmdSQL);
            }            }        }
    So, if we type in the page (no parameter's), then all hotels will show, but with above code, we can use that nice looking URL, and the result would thus be this:  

    User's image

    Again, note the nice clean - and "easy" to read URL used above.

    So, follow the above example, and you can thus convert your "old" style URL with parameter's to the above clean and easy to read format.

    In your example, it looks like you have/want this:


    Well, I think "search" is a less then ideal page to use. Pick a REALLY nice page name, one that suggests what you looking for.

    So, say


    I suppose you could have a page called Search.aspx, and then above would be this:


    So in above, the page is Search.aspx, and the 2 values are Plumbers and dar-elsalam.

    but, with above format, we could do this:


    However, some like often the reverse, so you could do it this way:



    Search/dar-elsalam/Auto Repeairs

    So, then your format is

      Search/ "some city goes here" /  "some category goes here"

    However, in ALL of the above cases, the values after Search.aspx page are a simple "array" of values (IList<string>)

    So, in your example of ../search/find?Syx=job=Plumber%20+%20state=CAIRO%20+%20city=ELSALAM%20DAR%20+%20.

    You might do it this way:

    Search/State/CAIRO/City/ElsAlam Dar/Jobs/Plumbers

    So, top most would be "state", then City, then "jobs" or (services!), then the catagory.

    so, in above then

      fURL = Request.GetFriendlyUrlSegments();  
     fURL[0] = "State"  
      fURL[1]  = "CAIRO" - the state  
     fURL[2] = "City"
     fURL[3] = "ElseAlam Dar  

    etc. etc. etc.

    So, once you have the "list" of values, YOU have to now write the code to break apart the values and have your code do whatever you need/want to do.

    but, as above shows, there is no need to YOUR code to re-write the URL's, you simple take the array/list of values, and have your code do whatever. So, once friendly URL's are turned on, then no further re-write rules or code is required. You be dealing with a array, and that array is "very" similar to that of query parameter's in a URL, but you use the above GetFriendlyUrlSegments in place of the query prams for the URL.

    Having stated all the the above? yes, I high recommend using friendly URL's, and they are great addition to any web site, and users really find them easy to read, and as noted, so easy are they to use, users will often type directly in the URL by hand as a result.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. QiYou-MSFT 4,311 Reputation points Microsoft Vendor

    Hi @Mohamed Saad

    Based on the material you gave, I have the following two understandings:

    1:Modify the address of the URL access:


    Change App_Start-Routeconfig.cs

    public static void RegisterRoutes(RouteCollection routes)
                var settings = new FriendlyUrlSettings();
                settings.AutoRedirectMode = RedirectMode.Permanent;

    'WebFormRoute': Routename

    "test/{query}": The URL you entered(with * for querystring)

    "~/About.aspx": Final address


    2.Rewrite the URL

    I think this document can help you: Document

    Best Regards,

    Qi You

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

  2. Karen Payne MVP 35,286 Reputation points

    Add the following class to your project. Then say a page named ProductName will be product-name.

    using System.Text.RegularExpressions;
    #pragma warning disable CS8603
    #pragma warning disable CS8767
    namespace TransformerSlugs.Classes;
    public class SlugingParameterTransformer : IOutboundParameterTransformer
        public string TransformOutbound(object value)
            if (value is null) { return null; }
            return Regex.Replace(value.ToString()!, "([a-z])([A-Z])", "$1-$2").ToLower();

    In Startup.cs, ConfigureServices add

        .AddRazorPagesOptions(options =>
                new PageRouteTransformerConvention(
                    new SlugingParameterTransformer()));