简体   繁体   中英

Getting list of friendlyURL and aspx page they belong to from RouteConfig.cs

I was wondering if there is an implemented way to get a list of objects from RouteConfig.cs, where I would have actual aspx page name and it's friendly URL equivalent. We work with the pagename in URL a lot and it's a pain in the *** to always check if the URL contains aspx page name in the path or the friendlyURL, as those pages could technically be accessed using both ways.

So say I have this in RouteConfig:

routes.MapPageRoute(
    "ResetPasswordRequestRoute",
    "reset-password",
    "~/Pages/PasswordResetRequestPage.aspx"
);

routes.MapPageRoute(
    "PatientRegistrationPageRoute",
    "registration",
    "~/Pages/Registration.aspx"
);

I want to implement something like this:

List<PageNames> PageNames = GetPageNamesFromRouteConfig();

Where the expected result looks like this:

List<PageNames>() {
    { new PageNames(){ 
        Page = PasswordResetRequestPage.aspx, 
        FriendlyURL = reset-password} 
    },
    { new PageNames(){ 
        Page = Registration.aspx, 
        FriendlyURL = registration} 
    },
}

If it cannot be done, I guess I can always read the RouteConfig.cs manually as text and separate each item in it and get it from there, I was just searching for an easier solution.

I guess nevermind, I did it the latter way. For anyone who also bumps into same problem, here is my solution, altough if you had RouteConfig.cs written in different way, you might need to do a few changes.

    /// <summary>
    /// Reads App_Start/RouteConfig.cs as file and exports List<PageNameAndFriendlyURL> from it as a collection of all mapped pages in the project
    /// </summary>
    /// <returns></returns>
    internal static List<PageNameAndFriendlyURL> GetPageNamesAndFriendlyURLs()
    {
        List<PageNameAndFriendlyURL> Output = new List<PageNameAndFriendlyURL>();
                
        string FullText = File.ReadAllText(HostingEnvironment.MapPath("~/App_Start/RouteConfig.cs"));
        List<string> Paragraphs = FullText.Split(new string[] { "routes.MapPageRoute" }, StringSplitOptions.None).Skip(1).ToList();
    
        foreach(string Text in Paragraphs)
        {
            string[] SplitText = Text.Split(new char[] { ',', ')' });
    
            Output.Add(new PageNameAndFriendlyURL()
            {
                Page = SplitText[2].Replace("\"", "").Replace("\r\n", "").Replace("~", "").Trim(),
                FriendlyURL = SplitText[1].Replace("\"", "").Replace("\r\n", "").Trim(),
            });
        }
    
        return Output;
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM