在 C# 中调用网络 api
Calling web api in c#
我正在尝试在本地调用我的网络api。这是我的邮递员 url,效果很好。 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);
}
}
注意:实际测试 return 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
{
我正在尝试在本地调用我的网络api。这是我的邮递员 url,效果很好。 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);
}
}
注意:实际测试 return 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
{