首页 > 解决方案 > window.location.href 将 HttpContext.Current.Request.Path 返回为“/”

问题描述

我有一个获取当前请求路径的过滤器。对于某些情况,我使用过

window.location.href =@Url.Action("Action","Controller"). 

通常HttpContext.Current.Request.Path返回Controller/Action,但如果window.location.href它总是返回"/"。我可以使用window.location.href重定向以外的其他方法来检索正确的路径吗?

标签: c#jqueryasp.net-mvc

解决方案


window.location.href需要一个 JavaScript 字符串,但您的代码会呈现无效的 JS,因为生成的 URLUrl.Action(...)没有被撇号或引号包围。

正确的代码是

window.location.href = '@Url.Action("Action","Controller")';

但是,我推荐HttpUtility.JavaScriptStringEncode作为一个完全安全的解决方案:

window.location.href = @HttpUtility.JavaScriptStringEncode(Url.Action("Action","Controller"), addDoubleQuotes: true);

推荐阅读