How to call Web API (App Service) remotely

霸气de小男生 提交于 2019-12-12 04:43:58

问题


I need to call an API from AppService by uri.

This is my 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 }
     };
}

I use this Function to call it:

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

I used Swagger to call Test_AddStudent successfully. The testJson was copied from Swagger when I call Test_AddStudent successfully.

After that, I used Swagger to call TestCallApi without any error, but when I tried to debug the value of HttpResponseMessage, it showed this error:

{
    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
    }
}

Have I missed something?


回答1:


I finally found the root cause: I passed the wrong input to the api:

Wrong:

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

Correct:

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


来源:https://stackoverflow.com/questions/47026840/how-to-call-web-api-app-service-remotely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!