如何在ASP.NET Core重写模块中使用{PATH_INFO}



我正试图将以下IIS重写规则移动到ASP.NET Core 3.1启动中。然而,当我这样做的时候,我得到了"System.FormatException:"无法识别的参数类型:"PATH_INFO",终止于字符串索引:"10"异常。"。根据Gitub问题,目前还不支持PATH_INFO。有没有一种方法可以让我在没有PATH_INFO的情况下工作?IIS重写规则:

<rewrite>
<rules>
<rule name="CamelCaseFormatRule" stopProcessing="true">
<match url=".*" ignoreCase="true" />
<action type="Redirect" url="/InstructionManual/{R:0}" logRewrittenUrl="true" />
<conditions>
<add input="{HTTP_HOST}" pattern="^localhost$" />
<add input="{PATH_INFO}" pattern="InstructionManual" ignoreCase="false" negate="true" />
</conditions>
</rule>
</rules>
</rewrite>

我已经把它放在我的应用程序根目录下的一个XML文件中,并在启动时这样调用它:

app.UseRewriter(new RewriteOptions((.AddIISUrlRewrite(env.ContentRootFileProvider,"redirectRule.config"((;

此规则检查请求是否具有驼色大小写的虚拟目录名(即InstructionManual(。如果没有,请将URL重建为正确的格式并重定向。

当我使用IIS模块时,此规则可以正常工作。以下是一些例子:

http://localhost/InstructionManual/?id=54 --> http://localhost/InstructionManual/?id=54
http://localhost/instructionmanual/?id=54 --> http://localhost/InstructionManual/?id=54
http://localhost/insTructionManuaL/?id=54 --> http://localhost/InstructionManual/?id=54

看起来我已经解决了自己的问题。我遵循了这里的解决方案:使用Asp.Net核心中间件将非WWW重定向到WWW

基于此,我修改了我的自定义规则为:

public virtual void ApplyRule(RewriteContext context)
{
var req = context.HttpContext.Request;
var p = req.Path;
string pathBase = req.PathBase;
var h = req.Host;
if (pathBase.Equals("/InstructionManual"))
{
context.Result = RuleResult.ContinueRules;
return;
} 
var wwwHost = new HostString($"{req.Host.Value}");
var newUrl = UriHelper.BuildAbsolute(req.Scheme, wwwHost, "/InstructionManual", req.Path, req.QueryString);
var response = context.HttpContext.Response;
response.StatusCode = 301;
response.Headers[HeaderNames.Location] = newUrl;
context.Result = RuleResult.EndResponse;
}

最新更新