客户端相对寻址并且在应用程序中不允许尾部斜杠 URL

Client-side relative addressing and allowing no trailing slash in application URL

我的 ASP.NET Core 3.1 有这个奇怪的问题,我的 ASP.NET 4 应用程序中没有,如果我通过

访问我的应用程序

http://example.com/Application/

然后一切正常,但如果我尝试去

http://example.com/Application(没有尾部斜杠)

然后客户端相对地址解析为 http://example.com/Resource 而不是 http://example.com/Application/Resource

关于应用程序的根,我遇到了类似的问题。例如,/Resource 似乎意味着相对于域,因此产生 http://example.com/ResourceResource 本身正确地产生 http://example.com/Application/Resource。但是如何引用 "root" 本身呢?重定向到空字符串似乎刷新页面而不是重定向到应用程序根目录。

我通过使用 . 并使用 ./Resource 而不是 Resource 解决了这个问题。这似乎在几乎所有情况下都有效,除非在没有结尾斜杠的情况下访问应用程序。

访问 http://example.com/Application 时,AJAX 调用以 ./Method?handler=name 形式的 URL 导致请求 http://example.com/Method?handler=name(缺少路径的 Application 部分).

如何让客户端相对地址始终指向正确的应用程序根地址?还是这可能是正常行为?

试试这个:

function stripSlashEnds(url){
  return url.replace(/^\/|\/$/g, '');
}
console.log(stripSlashEnds('http://example.com/Application/')+'/'+stripSlashEnds('/anotherFile/'));
console.log(stripSlashEnds('http://example.com/Application')+'/'+stripSlashEnds('/anotherFile'));

请注意,stripSlashEnds 只是删除字符串开头和结尾的前向斜线。您必须 +'/' 添加一个。

您需要将主模板中的基础url(ASP.NET Core MVC 中的_Layout.cshtml)设置为应用程序路径。

_Layout.cshtml中添加

<base href="~/"/>

~/ 是 ASP.NET Core 将替换为 http://example.com/Application 的应用程序路径(也称为 Web 根目录)。一般来说,如果你需要应用程序的相对路径,你应该总是做 <a href="~/app/relative/path"></a>.

当涉及静态 json 文件时,这可能会有点困难,因此 <base href="..."/> 在这种情况下应该有效