c# - 在 C# 中调用 web api
问题描述
我正在尝试在本地调用我的 webapi。这是我的邮递员网址,效果很好。http://localhost:8080/api/V1/Students
从 MVC 应用程序调用时,我得到一个未找到的异常 404。
这是我的学生控制器
var url = "/Students";
string test = ApiHelper.ApiClient.BaseAddress + url;
using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
listStudent = await response.Content.ReadAsAsync<List<StudentModel>>();
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
注意:测试实际返回的url是“ http://localhost:8080/api/V1/Students ”。巫他好。
这是我的 ApiHelper 代码。
public class ApiHelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
string ApiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"];
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri(ApiBaseUrl);
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
当我调试它时,我发现在我的响应中请求 URI
RequestUri {http://localhost:8080/Student}
这是我的 api 位置被调用的地方
<appSettings>
<add key="ApiUrl" value="http://localhost:8080/api/V1" />
</appSettings>
我在尝试调用本地 api 时做错了什么?
解决方案
api/v1 是一个路由前缀。再次使用此路由前缀和托盘装饰您的 BaseAddress 控制器。像这样:
[RoutePrefix("api/V1")]
public class ProductController : Controller
{
推荐阅读
- c# - 验证取消后不再调用方法
- php - 如何获取标头值,如果我们不知道该值,因为该值是来自服务器的随机值
- javascript - 在 Sails 版本 1 中使用sails-mongo 时无法加载钩子(`orm`)
- json - FullCalendar/Laravel JSON 事件提要,找不到控制器路由问题
- android - 如何正确创建 Firestore 集合查询的通知?
- ios - 带有自定义单元格的表格视图在滚动时会重复
- javascript - Angular/Rxjs 获取同步数据
- node.js - 在 Sequelize.js 中是否有存储执行(默认)的方法:记录到变量?
- azure-devops - 在“初始化作业”任务中运行自定义脚本
- java - APK 文件在手动安装时运行正常,但从 google play 商店安装时无法打开