在c#中调用web api

问题描述 投票:1回答:1

我想在本地调用我的webapi。这是我的邮递员的网址,它工作得很好。http:/localhost:8080apiV1Students)。

当从MVC应用程序中调用时,我得到了一个异常404 not found。

这是我的学生控制器

            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);
                }
            }

注意:测试实际返回的网址是"http:/localhost:8080apiV1Students". 巫师他的好。

而这是我的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.net asp.net-mvc-4 asp.net-web-api
1个回答
1
投票

apiv1是一个路由前缀。用这个路由前缀装饰你的BaseAddress控制器,然后再托盘。像这样。

[RoutePrefix("api/V1")]  
    public class ProductController : Controller  
    { 
© www.soinside.com 2019 - 2024. All rights reserved.