首页 > 解决方案 > 在 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 时做错了什么?

标签: c#asp.netasp.net-mvc-4asp.net-web-api

解决方案


api/v1 是一个路由前缀。再次使用此路由前缀和托盘装饰您的 BaseAddress 控制器。像这样:

[RoutePrefix("api/V1")]  
    public class ProductController : Controller  
    { 

推荐阅读