[英]IIS Url Rewrite Module: Get ApplicationPath
我正在寻找一种方法来重写url,以防url中的应用程序路径具有不同的大小写。 由于不同部署的应用程序路径可能不同,因此我需要动态访问它。 这有什么办法吗?
背景:
我正在设置cookie到应用程序路径的路径。 由于cookie路径区分大小写,我需要重写URL以防它们被错误地装入。 我还想有其他方法,不需要使用url重写模块。
例
假设对于一个部署,应用程序的别名是“ApplicationA”(对于另一个部署,别名可能是“ApplicationB”)。
http://<host>:<port>/<applicationA or Applicationa or APPLicationA etc.>/<rest of the url>
Redirect to
http://<host>:<port>/ApplicationA/<rest of the url>
不确定REWRITE在你的情况下是否正确运行,也许你应该使用REDIRECT(永久),但是下面的规则允许我在特定情况下获取应用程序名称:
<system.webServer>
<rewrite>
<rules>
<rule name="My Rule" stopProcessing="true">
<match url="^(.+)" ignoreCase="false" />
<conditions>
<add input="{REQUEST_URI}" pattern="TmP/.+" ignoreCase="false" negate="true" />
<add input="{REQUEST_URI}" pattern="tmp/(.+)" ignoreCase="true" />
</conditions>
<action type="Redirect" url="TmP/{C:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
我认为创建和添加自定义Http模块可以解决您的问题。 响应BeginRequest
和EndRequest
事件,在每个请求上调用HTTP模块。
您可以动态访问URL并通过更改其大小写重定向它。
private void PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
var f = req.Url;
f="Change case of URL";
if (condition)
{
app.Response.Redirect(f);
}
}
更新
我建议您使用HTTPModule订阅BeginRequest
事件。
使用RewritePath
方法,您可以获得Redirect
速度,如果外壳错误,您只需匹配并重写网址......或者实际上只是调整外壳可能比先检查它然后调整(测试并查看之前)你选择解决方案)。
一个积极的副作用是你可以轻松地进行其他测试并做出例外等。
public class AdjustCasingModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += OnBeginRequest;
}
protected void BeginRequest(object sender, EventArgs e)
{
var httpContext = ((HttpApplication)sender).Context;
string[] path = httpContext.Request.Path.Split('/');
if (path[1].Length > 0)
{
Regex rgx = new Regex(@"^[A-Z][a-z]*[A-Z]");
if (!rgx.IsMatch(path[1]))
{
char[] a = path[1].ToLower().ToCharArray();
a[0] = char.ToUpper(a[0]);
a[char.Length - 1] = char.ToUpper(a[char.Length - 1]);
path[1] = new string(a);
httpContext.RewritePath(String.Join('/', path));
}
}
}
public void Dispose()
{
}
}
边注:
我仍然建议首先使用小写路径。
只是一个想法,如果有人会考虑放弃使用驼峰案例表示法(ApplicationA)而强制使用例如小写*(applicationa),您可以使用ToLower关键字,如下所示。
<system.webServer>
<rewrite>
<rules>
<rule name="force lowercase" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{URL}" pattern="[A-Z]" ignoreCase="false" />
</conditions>
<action type="Redirect" url="{ToLower:{URL}}" redirectType="Temporary" />
</rule>
</rules>
</rewrite>
</system.webServer>
*如果您在网址中承诺使用原始的camelCase表示法,那么我将遵循Uriil的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.