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

ASP.NET MVC中如何获取带#锚点的URL外部参数?

如何在ASP.NET MVC中获取URL哈希(#)后的参数?

首先得明确一个关键:浏览器不会把URL中#后面的哈希片段(fragment)发送到服务器,这就是你用Uri的segments、PathAndQuery、Query等方法拿不到参数的原因。下面分两种场景给你解决方案:

场景1:前端直接提取并存储(推荐)

既然哈希是前端专属的内容,直接用JavaScript提取最省事,还能直接存到localStorage或者变量里:

// 截取#后面的参数部分,去掉开头的#
const hashStr = window.location.hash.slice(1);
// 用URLSearchParams解析成键值对
const params = new URLSearchParams(hashStr);

// 提取需要的参数
const accessToken = params.get('access_token');
const tokenType = params.get('token_type');
const expiresIn = params.get('expires_in');

// 存到localStorage
accessToken && localStorage.setItem('access_token', accessToken);
tokenType && localStorage.setItem('token_type', tokenType);
expiresIn && localStorage.setItem('expires_in', expiresIn);

// 或者存到变量供后续逻辑使用
const authInfo = {
  accessToken,
  tokenType,
  expiresIn
};

场景2:需要把参数传给服务器处理

如果必须让ASP.NET MVC后端拿到这些参数,得先让前端把哈希转成查询参数(?开头的那种),再跳转或提交请求:

const hashStr = window.location.hash.slice(1);
if (hashStr) {
  // 把哈希参数转成查询参数,跳转到当前路径的带参地址
  window.location.href = `${window.location.pathname}?${hashStr}`;
}

之后在你的Controller里,就可以用常规方式获取查询参数了:

public ActionResult Callback()
{
    string accessToken = Request.QueryString["access_token"];
    string tokenType = Request.QueryString["token_type"];
    string expiresIn = Request.QueryString["expires_in"];

    // 这里写你的后续处理逻辑
    return View();
}

补充说明

之前你尝试的服务器端方法失败,本质是因为HTTP请求里根本不包含#后的内容——浏览器在发送请求时会自动截断#及后面的部分,所以服务器端根本接收不到这部分数据,必须通过前端先处理。

内容的提问来源于stack exchange,提问作者Hafiz Waqar Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:35:27