ASP.NET Core 6 MVC:如何在Layout页面获取basePath/wwwroot路径
解决ASP.NET Core 6 MVC中获取项目根路径为空的问题
在ASP.NET Core 6 MVC的_Layout.cshtml中,你用Url.Content("~")获取根路径返回空字符串,这是因为Core版本里该方法的行为和传统ASP.NET不同。以下是几种可行的解决方案:
方案1:改用Url.Content("~/")
修改全局变量的赋值代码,把~改为~/,就能正确返回带末尾斜杠的应用根路径:
<script type="text/javascript"> var Global = Global || {}; Global.basePath = '@Url.Content("~/")'; </script>
方案2:使用Url.Action("", "")
调用无参数的Url.Action方法,同样可以生成应用根路径:
<script type="text/javascript"> var Global = Global || {}; Global.basePath = '@Url.Action("", "")'; </script>
方案3:获取完整绝对路径(适合跨域或需完整URL的场景)
如果AJAX请求需要包含协议、域名的完整绝对URL,可以通过请求上下文拼接:
<script type="text/javascript"> var Global = Global || {}; Global.basePath = '@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.PathBase}/")'; </script>
验证AJAX请求
修改后,你的AJAX代码可以正常拼接URL:
Admin.UpdateMainProductImage = function (imageId, isMain) { $.ajax({ url: Global.basePath + 'Admin/Product/UpdateImageIsMain', type: "GET", dataType: 'html', data: { imageId: imageId, isMain: isMain }, cache: false, success: function (data) { alert('Main Product Image updated successfully.'); }, error: function (xhr, status, error) { alert('Error updating image settings'); } }); }
内容的提问来源于stack exchange,提问作者JakeFromStateFarm
相关产品推荐
相关产品推荐

