【问题标题】:How to call Web API (App Service) remotely如何远程调用 Web API(应用服务)
【发布时间】:2017-10-31 02:03:32
【问题描述】:

我需要通过 uri 从 AppService 调用 API。

这是我的 API:

public ApiOutputBase Test_AddStudent(string name, int age, string address)
{
     return new ApiOutputBase
     {
          Result = new Result { Status = true, Message = "OK,Test_AddStudent Done!" },
          OuputValues = new List<object>() { name, age, address }
     };
}

我用这个函数来调用它:

public async Task<bool> TestCallApi()
{
     var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

     var testJson = "{\r\n    \"name\": \"MyName\",\r\n    \"age\": 25,\r\n    \"address\": \"MyAddress\"\r\n}";
     HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));

     // Call api success
     if (response.IsSuccessStatusCode)
     {
     }

     return true;
}

我使用 Swagger 成功调用了Test_AddStudent。当我成功调用Test_AddStudent 时,testJson 是从 Swagger 复制的。

之后,我用Swagger调用TestCallApi没有任何错误,但是当我尝试调试HttpResponseMessage的值时,却显示了这个错误:

{
    StatusCode: 400,
    ReasonPhrase: 'Bad Request',
    Version: 1.1,
    Content: System.Net.Http.StreamContent,
    Headers: {
        Pragma: no-cache
        Cache-Control: no-store, no-cache
        Date: Tue, 31 Oct 2017 02:12:45 GMT
        Set-Cookie: Abp.Localization.CultureName=en; expires=Thu, 31-Oct-2019 02:12:45 GMT; path=/
        Server: Microsoft-IIS/10.0
        X-AspNet-Version: 4.0.30319
        X-Powered-By: ASP.NET
        Content-Length: 405
        Content-Type: application/json; charset=utf-8
        Expires: -1
    }
}

我错过了什么吗?

【问题讨论】:

  • 显示你的错误日志。
  • 它已经在我的帖子里了,兄弟。我应该添加任何授权吗?
  • 这是一个 HTTP 响应。显示*.Web.Mvc\App_Data\Logs 中的错误日志。
  • 我多次尝试运行此功能,但找不到任何相关日志。注意:我使用swagger来调用这个函数
  • 大摇大摆?您的问题中HttpClient 是否有错误?

标签: c# asp.net-web-api aspnetboilerplate


【解决方案1】:

我终于找到了根本原因:我把错误的输入传递给了api:

错误:

var testJson = "{\r\n    \"name\": \"MyName\",\r\n    \"age\": 25,\r\n    \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));

正确:

HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent?name=MyName&age=25&address=MyAdress", "");

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 2014-12-25
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2011-07-05
    • 2019-06-02
    相关资源
    最近更新 更多