You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取当前位置的Base URL?寻求适配两种场景的通用方案

Flexible Base URL Extraction for Two Scenarios

Great question! Let’s work through a universal solution that handles both your URL cases smoothly. The key is to parse the URL into its core components and combine the right pieces—whether you’re working frontend, backend, or need a regex-based approach.

Frontend JavaScript Solution

Modern browsers have the built-in URL object that makes parsing a breeze. This method checks if there’s an application context path (like /myApp) vs. just a direct page under the root:

function getBaseUrl() {
  const currentUrl = new URL(window.location.href);
  let baseUrl = currentUrl.host; // Grabs "localhost:6111" or "localhost"

  // Split path into segments, filter out empty strings from leading/trailing slashes
  const pathSegments = currentUrl.pathname.split('/').filter(seg => seg !== '');
  
  // If the first segment isn't a file (no dot in the name), it's an app context path
  if (pathSegments.length > 0 && !pathSegments[0].includes('.')) {
    baseUrl += `/${pathSegments[0]}`;
  }

  return baseUrl;
}

// Test results:
// Scenario 1: "http://localhost:6111/Page.aspx" → returns "localhost:6111"
// Scenario 2: "http://localhost/myApp/Page.aspx" → returns "localhost/myApp"

Backend C# Solution (ASP.NET)

Since your example uses .aspx, this ASP.NET-specific approach leverages framework built-ins to avoid manual parsing—super reliable:

public string GetBaseUrl()
{
    HttpRequest request = HttpContext.Current.Request;
    string host = request.Url.Host;

    // Add port if it's not the default (80 for HTTP, 443 for HTTPS)
    if (!request.Url.IsDefaultPort)
    {
        host += $":{request.Url.Port}";
    }

    // Append application path if it exists (not root "/")
    string appPath = request.ApplicationPath;
    if (!string.IsNullOrEmpty(appPath) && appPath != "/")
    {
        host += appPath;
    }

    return host;
}

The Request.ApplicationPath property automatically grabs your app's context root (like /myApp), so it perfectly adapts to both scenarios without extra logic.

General Regex Approach (Cross-Language)

If you need a string-only solution that works across languages, this regex targets the host and optional app context path, skipping the protocol and page file:

^(?:https?:\/\/)?([^\/]+)(?:\/([^\/\.]+))?

Example Usage (JavaScript)

function getBaseUrlWithRegex(urlString) {
  const baseUrlRegex = /^(?:https?:\/\/)?([^\/]+)(?:\/([^\/\.]+))?/;
  const match = urlString.match(baseUrlRegex);

  if (!match) return '';

  let baseUrl = match[1];
  // Add the app context path if captured
  if (match[2]) baseUrl += `/${match[2]}`;

  return baseUrl;
}

// Test:
console.log(getBaseUrlWithRegex("http://localhost:6111/Page.aspx")); // "localhost:6111"
console.log(getBaseUrlWithRegex("http://localhost/myApp/Page.aspx")); // "localhost/myApp"

This regex works by:

  1. Ignoring the optional http:///https:// prefix
  2. Capturing the host (including port) until the first slash
  3. Optionally capturing a path segment that doesn't contain a dot (to avoid matching page files like Page.aspx)

Final Notes

  • Prefer built-in APIs (like URL in JS or ASP.NET's Request properties) over regex when possible—they handle edge cases (like non-standard ports, HTTPS) more reliably.
  • If you have deeper path structures (e.g., http://localhost/myApp/sub/Page.aspx), all these methods will still return localhost/myApp, which aligns with typical base URL expectations for an application root.

内容的提问来源于stack exchange,提问作者iamnotgoodatcoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:13:13