ASP.NET C#如何将接口返回的JSON结果显示到TextBox而非控制台输出
ASP.NET C# 环境下将CoinMarketCap接口返回结果绑定到TextBox控件的方案
你目前的前端JS直接调用接口的写法存在CORS跨域限制问题,浏览器大概率会拦截请求,下面提供两种可行方案:
前端JS直接赋值方案(仅适用于已解决跨域的场景)
- 首先修改页面内的TextBox控件配置,设置
ClientIDMode="Static"保证前端可直接通过ID获取DOM:
<asp:TextBox ID="txtMarketCap" runat="server" ClientIDMode="Static" Width="600px" TextMode="MultiLine" Height="200px"></asp:TextBox>
- 修改你的JS代码,将
console.log替换为TextBox赋值逻辑:
<script> var apikey = { key:'XXX' } request('GET', 'https://pro-api.coinmarketcap.com/v1/global-metrics/quotes/latest?CMC_PRO_API_KEY=' + apikey.key).then((r1) => { var x1 = JSON.parse(r1.target.responseText); // 仅显示总市值字段 // document.getElementById('txtMarketCap').value = x1.data.quote.USD.total_market_cap; // 显示格式化后的完整JSON结果 document.getElementById('txtMarketCap').value = JSON.stringify(x1, null, 2); }).catch(err => { document.getElementById('txtMarketCap').value = '请求出错:' + err; }) function request(method, url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = resolve; xhr.onerror = reject; xhr.send(); }); } </script>
后端C#代理请求方案(推荐,无跨域问题)
- 若需要解析JSON提取指定字段,先通过NuGet安装
Newtonsoft.Json包,仅显示原始JSON可跳过此步 - 编写aspx.cs后端代码:
using System; using System.Net.Http; using System.Threading.Tasks; // 解析JSON需额外引用 // using Newtonsoft.Json.Linq; public partial class YourPage : System.Web.UI.Page { // 全局静态HttpClient实例,避免重复创建导致资源浪费 private static readonly HttpClient _httpClient = new HttpClient(); protected async void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string apiKey = "你的CoinMarketCap API密钥"; string requestUrl = $"https://pro-api.coinmarketcap.com/v1/global-metrics/quotes/latest?CMC_PRO_API_KEY={apiKey}"; try { string responseJson = await _httpClient.GetStringAsync(requestUrl); // 直接显示原始JSON txtMarketCap.Text = responseJson; // 解析后仅显示总市值的写法 // JObject result = JObject.Parse(responseJson); // txtMarketCap.Text = result["data"]["quote"]["USD"]["total_market_cap"].ToString(); } catch (Exception ex) { txtMarketCap.Text = $"接口请求失败:{ex.Message}"; } } } }
内容的提问来源于stack exchange,提问作者Black
相关产品推荐
相关产品推荐

