Determing the physical path of a user friendly url

喜夏-厌秋 提交于 2019-12-25 02:14:58

问题


I have been asked to look at updating an old ASP.net Web Forms application to ASP.net 4.5; specifically to implement Microsoft's 'User Friendly' routing mechanism (NuGet Package Microsoft.AspNet.FriendlyUrls).

Generally, the upgrade was straightforward, but I am left with one problem.

The original developer attached/associated 'meta data' XML files to many of the web pages.. For example, /Products/Tables/Oak.aspx might also have the following meta file /Products/Tables/Oak.aspx.meta

When the page loads, it 'looks' for the meta file and loads it. In a non-rewritten URL environment, this was easy...

string metaUrl = Page.Request.Url.AbsolutePath + ".meta";
string metaPath = Page.Server.MapPath(metaUrl);
If (System.IO.File.Exists(metaPath)) {
   LoadMetaFile(metaPath);
}

In a 'Friendly URL' environment, this is not so easy as the original URL might be rewritten to /Products/Tables/Oak or maybe even rewritten completely via a custom MapPageRoute() definition.

Does anyone know if there a way that I can find/determine the 'true' path of the page?


回答1:


The solution posted by Petriq ASP.NET WebForms: Request.GetFriendlyUrlFileVirtualPath() returns empty string works perfectly in my scenario.

For reference, here is Petriq's code for his HttpRequest extension method:

using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace Utils.Extensions
{
   public static class HttpRequestExtensions
   {
       public static string GetFileVirtualPathFromFriendlyUrl(this HttpRequest request) 
       {
          string ret = string.Empty;

          ret = request.GetFriendlyUrlFileVirtualPath();

          if (ret == string.Empty)
          {
            foreach (RouteBase r in RouteTable.Routes)
            {
                if (r.GetType() == typeof(Route))
                {
                    Route route = (Route)r;
                    // Following line modified for case-insensitive comparison
                    if (String.Compare("/" + route.Url, request.Path, true) == 0)
                    {
                        if (route.RouteHandler.GetType() == typeof(PageRouteHandler))
                        {
                            PageRouteHandler handler = (PageRouteHandler)route.RouteHandler;

                            ret = handler.VirtualPath;
                        }
                        break;
                    }
                }
            }
          }

          return ret;
       }
   }
}


来源:https://stackoverflow.com/questions/22577826/determing-the-physical-path-of-a-user-friendly-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!