Asp.net mvc 4 缺少尾部斜杠的MVC错误行为的解决方法

Asp.net mvc 4 缺少尾部斜杠的MVC错误行为的解决方法,asp.net-mvc-4,iis,requirejs,Asp.net Mvc 4,Iis,Requirejs,这在index.cshtml中 <script>alert(window.location.href);</script> <script type="text/javascript" src="~/Scripts/require.js" data-main="App/main"> </script> 但这只会使问题更加明显;当有尾随斜杠时,浏览器继续工作,但现在当没有尾随斜杠时,它会弹出一个充满原始HTML的消息对话框 以下是

这在index.cshtml中

<script>alert(window.location.href);</script>
<script 
  type="text/javascript" 
  src="~/Scripts/require.js" 
  data-main="App/main">
</script>
但这只会使问题更加明显;当有尾随斜杠时,浏览器继续工作,但现在当没有尾随斜杠时,它会弹出一个充满原始HTML的消息对话框

以下是几种可能的解决方案:

  • 将IIS配置为在到达ASP.NET之前附加尾部斜杠
  • 设置MVC应用程序以尽早检查此问题,并使用尾部斜杠重定向
让IIS这样做可能不是最好的计划。配置更改很可能会导致系统的其他方面出现问题,特别是对于多页(非SPA)MVC应用程序。其余的习惯是将参数编码到URL中,就像它们是资源路径一样,传统上不使用尾随斜杠

有人可能会说,这种表示法与传统的URL参数编码相比没有添加任何内容,并且违反了HTTP规范(更不用说真正的HTTP规范了),但是这种编码类型有相当大的投资,因此作为解决方案,服务器配置不太理想。

执行“礼貌重定向”在MVC应用程序中,打开主控制器并更新索引操作。在我的例子中,该应用程序是Durandal SPA应用程序,因此主索引方法如下所示:

public class DurandalController : Controller
{
  public ActionResult Index()
  {
    return View();
  }
}
public class DurandalController : Controller
{
  public ActionResult Index()
  {
    var root = VirtualPathUtility.ToAbsolute("~/");
    if ((root != Request.ApplicationPath) && (Request.ApplicationPath == Request.Path))
      return Redirect(root + "#");
    else
      return View();
  }
}
我们需要检查请求,必要时进行重定向。结果是这样的:

public class DurandalController : Controller
{
  public ActionResult Index()
  {
    return View();
  }
}
public class DurandalController : Controller
{
  public ActionResult Index()
  {
    var root = VirtualPathUtility.ToAbsolute("~/");
    if ((root != Request.ApplicationPath) && (Request.ApplicationPath == Request.Path))
      return Redirect(root + "#");
    else
      return View();
  }
}

重定向在SPA应用程序的会话生命周期中只起一次作用,因为每个会话仅从服务器加载一次重定向。这样实现对其他控制器及其处理的URL没有影响。

谢谢您的有用帖子

我不知道为什么,但对我来说,在一些ASP应用程序中,Request.ApplicationPath和Request.Path并不是严格相等的,所以我必须忽略大小写

因此,一个小的改进可能是:

var root = VirtualPathUtility.ToAbsolute("~/");
if ((!root.Equals(Request.ApplicationPath, System.StringComparison.CurrentCultureIgnoreCase))
    && (Request.ApplicationPath.Equals(Request.Path, System.StringComparison.CurrentCultureIgnoreCase)))
{
    return Redirect(root + "#");
}
else
{
    return View();
}

接得好。你说得很对,它不区分大小写时更健壮。