Asp.net 4.7 url rewrite

Asap74 61 Reputation points
2022-11-15T09:56:43.21+00:00

Hi,
How Is possibile to have aspx files and directory to be processed and URL rewritten?
I mean:
URL: mydomain.com/pippo.aspx that dont exists must become mydomain.com/default.aspx?id=Pippo

Thanx

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,396 questions
{count} votes

Accepted answer
  1. Deepak-MSFT 2,191 Reputation points Microsoft Vendor
    2022-11-17T02:58:51.803+00:00

    Hi @Asap74 ,

    I would suggest you try to use the Application_BeginRequest event to process the URL. then in the code logic, you could try to check whether the page exists or not and based on that you could redirect the page.

    Below is the sample code. You need to add it to the Global.asax.cs file.

     protected void Application_BeginRequest(object sender, EventArgs e)  
            {  
                try  
                {   
                    string path = HttpContext.Current.Request.Path;  
      
                        if (path.ToLower().Contains(".aspx"))  
                        {  
                                string filename = path.Substring(path.LastIndexOf('/') + 1);  
      
                                bool res = IsFileExists(filename);  
      
                                if(res==true)  
                                {   
                                    //Do nothing...  
                                }  
                                else  
                                {  
                                    string page = filename.Substring(0, filename.LastIndexOf("."));  
                                    Response.Redirect("https://localhost:44326/default.aspx?id=" + page);  
                      
                                }  
                        }  
                }  
                catch { }  
            }  
            private bool IsFileExists(string fileName)  
            {  
                string rootWebDirectory = Server.MapPath(fileName);  
                return File.Exists(rootWebDirectory);  
      
            }  
    

    Output:

    261138-20.gif

    Further, you could modify the code sample as per your requirement.

    Best Regards,
    Deepak

    ----------

    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.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful