[英]Calling web api in c#
I am trying to call my webapi locally.我正在尝试在本地调用我的 webapi。 This is my postman url and it work great.
这是我的 postman url,效果很好。 http://localhost:8080/api/V1/Students
http://localhost:8080/api/V1/Students
When calling from MVC application I get an exception 404 not found.从 MVC 应用程序调用时,我得到一个未找到的异常 404。
This is my student controller这是我的学生 controller
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);
}
}
Notice: test actually return the url " http://localhost:8080/api/V1/Students ".注意:测试实际返回 url " http://localhost:8080/api/V1/Students "。 Witch his good.
巫他好。
And this is my ApiHelper code.这是我的 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"));
}
}
When I debug it I found that on my response the Request URI当我调试它时,我发现在我的响应中请求 URI
RequestUri {http://localhost:8080/Student}
This is where my api location is called这是我的 api 位置被调用的地方
<appSettings>
<add key="ApiUrl" value="http://localhost:8080/api/V1" />
</appSettings>
What I am doing wrong in trying to call the local api?我在尝试调用本地 api 时做错了什么?
api/v1 is a route prefix. api/v1 是一个路由前缀。 Decorate your BaseAddress controller with this route prefix and tray again.
再次使用此路由前缀和托盘装饰您的 BaseAddress controller。 Like so:
像这样:
[RoutePrefix("api/V1")]
public class ProductController : Controller
{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.