如何在ASP.NET Core 7 MVC项目中配置ASP.NET Core 7 Web API的URL?
在ASP.NET Core 7 MVC中配置并调用Web API的步骤
1. 配置API地址
1.1 存储API地址到配置文件
打开MVC项目的appsettings.json,添加API地址配置项,推荐优先使用HTTPS地址,HTTP作为备用:
{ "ApiSettings": { "HttpsBaseUrl": "https://localhost:7271", "HttpBaseUrl": "http://localhost:5122" } }
1.2 注册HttpClient服务
在MVC项目的Program.cs中注册HttpClient,绑定API基地址,后续可直接注入使用:
var builder = WebApplication.CreateBuilder(args); // 读取配置里的HTTPS地址作为默认基地址 var apiBaseUrl = builder.Configuration["ApiSettings:HttpsBaseUrl"]; // 注册命名HttpClient builder.Services.AddHttpClient("ApiClient", client => { client.BaseAddress = new Uri(apiBaseUrl); // 统一设置请求头,指定接收JSON格式 client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); }); // 注册MVC服务 builder.Services.AddControllersWithViews(); var app = builder.Build(); // 中间件配置(如静态文件、路由、授权等) app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
2. 在控制器中调用API
在目标控制器中通过构造函数注入IHttpClientFactory,创建HttpClient发起API请求:
using System.Net.Http.Json; using Microsoft.AspNetCore.Mvc; public class ApiTestController : Controller { private readonly IHttpClientFactory _httpClientFactory; public ApiTestController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public async Task<IActionResult> GetApiData() { var client = _httpClientFactory.CreateClient("ApiClient"); // 调用API的示例接口(替换为你的实际API路径) var response = await client.GetAsync("/api/products"); if (response.IsSuccessStatusCode) { // 读取返回的JSON数据(替换为你的实体类型) var products = await response.Content.ReadFromJsonAsync<List<Product>>(); return View(products); } else { ViewBag.ErrorMsg = $"API请求失败,状态码:{response.StatusCode}"; return View(); } } } // 示例实体类(根据你的API返回结构调整) public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
补充说明
- 若需要切换HTTP地址,可在
Program.cs中读取HttpBaseUrl替换apiBaseUrl,或注册两个命名HttpClient分别对应HTTPS和HTTP地址。 - 如果API需要身份验证,可在注册HttpClient时添加默认授权头,或在请求时动态设置。
内容的提问来源于stack exchange,提问作者Priya
相关产品推荐
相关产品推荐

