How to add custom url while using asp.net friendly urls

Mohamed Saad 20 Reputation points
2023-04-24T22:15:37.4133333+00:00
I Need your Help Please; I'm developing a asp.net 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;
            }
            else
            {
                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

        RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
        
    }
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)

.../search/find?Syx=job=Plumber%20+%20state=CAIRO%20+%20city=ELSALAM%20DAR%20+%20
How to make Up URL become

.../search/plumber-in-dar-elsalam
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");
after

routes.EnableFriendlyUrls(settings,new WebMethodFriendlyUrlResolver());
But didn’t work ☹️
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,419 questions
C#
C#
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,651 questions
{count} votes

Accepted answer
  1. Albert Kallal 5,231 Reputation points
    2023-04-26T17:07:37.25+00:00

    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 asp.net.

    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 asp.net page called Hotels. (to display some hotels).

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

    .Hotels.aspx?City="Edmonton"
    

    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:

    Hotels/City/Edmonton

    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:

     Hotels/Invoice/333522
    

    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"  >
            <Columns>
                <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">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkActive" runat="server" 
                            Checked='<%# Eval("Active") %>'/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="cmdView" runat="server" Text="View" 
                            OnClick="cmdView_Click" Height="32px" CssClass="btn" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    
    

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

    Hotels/City/Edmonton
    

    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);
                    GridView1.DataBind();
                }
            }            }        }
    
    
      
    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:

    ../search/plumber-in-dar-elsalam

    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

    Plumbers/dar-elsalam  
    

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

    Search/Plumbers/dar-elsalam  
    

    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:

    Search/ApplianceRepair/dar-elsalam     
    

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

     Search/dar-elsalam/Plumbers  
    

    or

    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
    2023-04-25T07:34:52.04+00:00

    Hi @Mohamed Saad

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

    1:Modify the address of the URL access:

    Example:

    Change App_Start-Routeconfig.cs

    public static void RegisterRoutes(RouteCollection routes)
            {
                var settings = new FriendlyUrlSettings();
                settings.AutoRedirectMode = RedirectMode.Permanent;
                routes.EnableFriendlyUrls(settings);
                routes.MapPageRoute("WebFormRoute",
               "test/{*query*}",
               "~/About.aspx");
            }
    

    'WebFormRoute': Routename

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

    "~/About.aspx": Final address

    Test4

    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,386 Reputation points
    2023-04-25T10:53:26.4466667+00:00

    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

    services.AddMvc()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.Add(
                new PageRouteTransformerConvention(
                    new SlugingParameterTransformer()));
        });