如何在jQuery中获取与@Request.ApplicationPath等效的路径值?
@Request.ApplicationPath in Standalone jQuery/JS File Got it, let's solve this problem—you want to ditch the Razor dependency in your standalone JS file while still grabbing that exact application root path that @Request.ApplicationPath provides (either / locally or /ProjectNameOnServer on your server).
The Core Issue
window.location.protocol + "//" + window.location.host only gives you the domain and protocol, but you need the virtual application root path that sits after the domain. That's exactly what @Request.ApplicationPath delivers: the root path of your web app relative to the server's host.
Pure JS Solution (No Razor Dependency)
The most reliable way to get this path without Razor is to leverage the script tag that loads your standalone JS file. Since your JS file lives at a path relative to the application root, we can parse its URL to extract the root:
function getApplicationPath() { // Grab the last loaded script tag (which should be your standalone JS file) const scripts = document.getElementsByTagName('script'); const currentScript = scripts[scripts.length - 1]; const scriptSrc = currentScript.src; // Adjust this folder name to match where your JS files live (e.g., /js/ instead of /Scripts/) const rootEndIndex = scriptSrc.indexOf('/Scripts/'); if (rootEndIndex === -1) { // Fallback logic if the script path doesn't match the expected folder const pathSegments = window.location.pathname.split('/').filter(segment => segment); // Return "/" if running at the root if (pathSegments.length === 0) return '/'; // Return the virtual directory path if present return `/${pathSegments[0]}`; } // Extract the base URL up to the /Scripts/ folder const baseUrl = scriptSrc.substring(0, rootEndIndex); // Convert to a URL object to easily get the pathname part const baseUri = new URL(baseUrl).pathname; // Match @Request.ApplicationPath's format (no trailing slash unless it's the root) return baseUri.endsWith('/') ? baseUri.slice(0, -1) : baseUri; } // Use the function to set your settings const settings = {}; settings.baseUri = getApplicationPath(); // Build your submission URL cleanly (no conditional checks needed!) const submissionUrl = new URL('api/apiControllerName/apiControllerMethodName/', `${window.location.origin}${settings.baseUri}`).href;
Why This Works
- If your app runs locally at
http://localhost:5000/Scripts/app.js, the function extracts/as the base URI. - If it runs on the server at
http://yourdomain.com/ProjectNameOnServer/Scripts/app.js, it extracts/ProjectNameOnServer. - Using
new URLto build the submission URL automatically handles slash inconsistencies, so you don't have to mess with conditional checks for/vs. non-root paths.
Alternative (If You Can Tolerate Tiny Razor Usage)
If you're okay with a tiny bit of Razor in your layout file (to avoid parsing scripts), you can define a global variable once and reuse it in your standalone JS:
In your layout page (e.g.,
_Layout.cshtml):<script> window.appConfig = { baseUri: '@Request.ApplicationPath' }; </script>Then in your standalone JS:
const settings = {}; settings.baseUri = window.appConfig.baseUri; const submissionUrl = new URL('api/apiControllerName/apiControllerMethodName/', `${window.location.origin}${settings.baseUri}`).href;
This is simpler, but it does keep a small Razor dependency. Pick whichever fits your goal of "removing Razor from JS files" best.
内容的提问来源于stack exchange,提问作者Grizzly

