本文介绍了如何远程调用Web API(应用程序服务)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过uri从AppService调用API.
I need to call an API from AppService by uri.
这是我的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;
}
我使用Swagger成功调用了Test_AddStudent
.当我成功调用Test_AddStudent
时,从Swagger复制了testJson
.
I used Swagger to call Test_AddStudent
successfully. The testJson
was copied from Swagger when I call Test_AddStudent
successfully.
此后,我使用Swagger调用了TestCallApi
,没有任何错误,但是当我尝试调试HttpResponseMessage
的值时,它显示了此错误:
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
}
}
我错过了什么吗?
推荐答案
我终于找到了根本原因:我将错误的输入传递给api:
I finally found the root cause: I passed the wrong input to the 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", "");
这篇关于如何远程调用Web API(应用程序服务)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!