【问题标题】:Calling web api in c#在 C# 中调用 web api
【发布时间】:2020-10-02 17:38:52
【问题描述】:

我正在尝试在本地调用我的 webapi。这是我的邮递员网址,效果很好。 http://localhost:8080/api/V1/Students

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

注意:测试实际返回的 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/Students而不是/Students调用GetAsync(url)
  • 这完成了工作,但是为什么我要把 api/v1 放在我所有的 web api 中,这听起来有点矫枉过正。
  • 我不知道您是如何定义 API 的路由的,但我尝试仅添加 [Route("api/V1/[controller]")] 并通过 GetAsync("/Students") 调用它。它工作正常
  • 不,我的意思是如果我执行 GetASync(api/V1/Students) 它可以工作,但是为每个控制器/方法声明 [route(...)] 似乎很乏味在每个方法/控制器上。如果我想从 v1 更改为 v2,那么我需要将我的所有方法从 route(api/v1... 更改为 route(api/v2...) 这就是为什么我创建了 apihelper 所以我可以拥有我的基础元素在一个中心位置。您的解决方案,但在每个控制器上。将来我可能有数千个控制器。但是是的,您的解决方案确实有效。
  • 在这种情况下,通过测试 GetAsync 方法更改 url。并将努力

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 2019-01-08
    • 2014-01-08
    • 1970-01-01
    • 2014-04-19
    • 2019-06-14
    • 1970-01-01
    • 2022-11-22
    • 2015-12-19
    相关资源
    最近更新 更多