簡體   English   中英

如何遠程調用Web API(應用程序服務)

[英]How to call Web API (App Service) remotely

我需要通過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 testJson從揚鞭復制當我打電話Test_AddStudent成功。

之后,我使用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
    }
}

我錯過了什么嗎?

我終於找到了根本原因:我將錯誤的輸入傳遞給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", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM