ASP.NET MVC to ignore “.html” at the end of all url

后端 未结 7 646
心在旅途
心在旅途 2021-01-04 18:52

I am new to asp.net mvc and now struggling with url routing. I\'m using asp.net mvc 3 RC2.

How can I create a url routing that IGNORES the very end

7条回答
  •  清酒与你
    2021-01-04 19:39

    Using the Application_BeginRequest, will allow you to intercept all incoming requests, and allow you to trim the extension. Make sure to ignore requests for your content, such as .css, .js, .jpg, etc. Otherwise those requests will have their extensions trimmed as well.

    protected void Application_BeginRequest(object sender, EventArgs e)
            {
                String originalPath = HttpContext.Current.Request.Url.AbsolutePath;
    
                //Ignore content files (e.g. .css, .js, .jpg, .png, etc.)
                if (!Regex.Match(originalPath, "^/[cC]ontent").Success)
                {
                    //Search for a file extension (1 - 5 charaters long)
                    Match match = Regex.Match(originalPath, "\\.[a-zA-Z0-9]{1,5}$");
    
                    if (match.Success)
                    {
                        String modifiedPath = String.Format("~{0}", originalPath.Replace(match.Value, String.Empty));
                        HttpContext.Current.RewritePath(modifiedPath);
                    }
                }
            }
    

提交回复
热议问题