ASP.NET Core 2.0部署到IIS后JavaScript无法运行求助
Hey Andrew, let's dig into why your site.js isn't loading on IIS even though it works locally—this is a super common gotcha when moving from dev to deployment, so we'll fix it step by step.
1. 先确认JS文件的引用路径是否正确
First off, the most likely culprit is that your script reference in _Layout.cshtml is using a relative path that doesn't resolve correctly on IIS. Local dev (IIS Express) might run from the root, but on a full IIS site, if your app is deployed as a sub-application or the site root is different, relative paths break.
Check your current reference in _Layout.cshtml—if it looks like this:
<script src="js/site.js"></script>
Change it to use ASP.NET's URL helper to resolve the root path properly:
<script src="@Url.Content("~/js/site.js")"></script>
Or if you're using MVC with Tag Helpers enabled, this works too:
<script asp-src="~/js/site.js"></script>
The ~ tells ASP.NET to resolve from the application root, no matter where your site is hosted.
2. 验证IIS是否启用了静态文件支持
Full IIS doesn't always have static file handling turned on by default (especially if it's a fresh install). If IIS can't serve .js files at all, that's exactly the behavior you'll see.
To check:
- Open IIS Manager, navigate to your site
- Go to Features View and look for Static Files
- If it's missing, open Server Manager > Add Roles and Features, navigate to Web Server (IIS) > Web Server > Common HTTP Features, and check Static Files to install it.
3. 检查文件和文件夹权限
Even if the site.js file exists on the server, the IIS application pool identity might not have permission to read it. Here's how to fix that:
- Navigate to the folder containing site.js on your server
- Right-click > Properties > Security
- Click Edit > Add
- Type
IIS_IUSRS(orNETWORK SERVICEdepending on your IIS version) and click Check Names to confirm - Give this user Read & Execute permissions, then apply the changes.
4. 排除浏览器缓存干扰
Sometimes browsers hang onto old cached versions of files, even if the server has the correct one. Force a full refresh with Ctrl + F5 to bypass cache, or add a version query string to your script reference to force the browser to fetch the latest file:
<script src="@Url.Content("~/js/site.js?v=20240520")"></script>
Just update the version number whenever you change the JS file.
5. 检查IIS请求筛选规则
It's possible IIS is blocking requests to .js files. To verify:
- In IIS Manager, go to your site > Request Filtering
- Switch to the File Name Extensions tab
- Make sure
.jsis in the list of allowed extensions. If not, click Add and enter.jsto allow it.
Once you try these steps, reload your site and check the Network tab again—site.js should load, and your menu click functionality should start working.
内容的提问来源于stack exchange,提问作者Andrew Simpson

