如何远程调用Web API(App Service)

时间:2017-10-31 02:03:32

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

我需要通过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复制。

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

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

我终于找到了根本原因:我将错误的输入传递给了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", "");