url 重写角度 ASP.NET



我正在使用URL重写,以便如果用户重新加载页面,他应该降落在他重新加载的同一视图上。在某种程度上,我得到了我想要的。我有 3 个目录管理员和用户以及一个根。我已经为所有三种情况编写了重写规则。单独所有三个都工作正常,即如果我一次使用一个,它对各自的目录工作正常,但如果尝试在其他目录中重新加载页面,url 保持不变,但呈现的页面来自另一个目录。例如,我在用户目录下打开了一个页面,加载的视图是 myprofile,所以现在如果我首先保留用户目录的规则,它将正常工作,但在这种情况下,假设我在管理员下,那么如果我重新加载 url 将是相同的,但呈现的页面将是用户的默认页面,但加载的视图将来自管理员。同样的事情也会发生在其他情况下。以下是我的规则

   <rule name="Admin Redirect Rule" stopProcessing="true">
      <match url="/(Admin)*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
      </conditions>
      <action type="Rewrite" url="/Admin/Admin.aspx" />
    </rule>
    <rule name="User Redirect Rule" stopProcessing="true">
      <match url="/(Users)*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
      </conditions>
      <action type="Rewrite" url="/Users/User.aspx" />
    </rule>

无法弄清楚我哪里出错了。因为单独两个规则都工作正常。但是当两者都包括在内时。尽管加载的视图正确,但呈现的基本页面正在更改。以下是我的目录结构

Root
----Users
     -----User.aspx
----Admin
     -----Admin.aspx

任何帮助将不胜感激。谢谢!

经过很多天的挣扎,仍然无法解决这个问题,但想出了另一种解决方案。共享解决方案。希望它可以帮助其他人。我们在这里的目标是重写 url,以便我们实际到达我们请求的视图。因此,为此,我使用了这种方法,我们为 asp.net 应用程序提供了一个Application_BeginRequest事件/方法。这是在服务器处理每个请求之前执行的。我们可以使用此方法进行 url 重写 这里有一个简单的例子。

protected void Application_BeginRequest(object sender, EventArgs e)
{
    // Get current path
    string CurrentPath = Request.Path;
    HttpContext MyContext = HttpContext.Current;
    Regex regex = new Regex(@"^/");
    Match match = regex.Match(CurrentPath);
    // Now we'll try to  rewrite URL in form of example format:
    // Check if URL  needs rewriting, other URLs will be ignored
    if (CurrentPath.IndexOf("/Users/") > -1 )
    {
        // I will use  simple string manipulation, but depending
        // on your case,  you can use regular expressions instead
        // Remove /  character from start and beginning
        // Rewrite URL to  use query strings
        MyContext.RewritePath("/Users/User.aspx");
    }
    else if (CurrentPath.IndexOf("/Admin/") > -1)
    {
        MyContext.RewritePath("/Admin/Admin.aspx");
    }
    else if (match.Success)
    {
        MyContext.RewritePath("/Default.aspx");
    }
}

因此,上面的代码将根据请求的 url 重写相应的 url。 与 url 重写相同。希望对您有所帮助。

最新更新