有一个我要更改为Post的Get方法
[HttpGet]
public IHttpActionResult Expiry(int id)
{
return Ok(_socialChorusService.Expiry(id));
}
获取方法更改为发布
[HttpPost]
public IHttpActionResult Expiry([FromBody]int id)
{
return Ok(_socialChorusService.Expiry(id));
}
创建请求时,如何传递整数
我可以通过字符串
进行以下操作var queryString = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>{new KeyValuePair<string, string>("id", id.toString())});
apiResponse = apiClient.PostAsync(requestUri, queryString).Result;
但是我想传递一个整数。是可能的,还是只是字符串可以在体内传递?
任何建议将不胜感激,
预先感谢
答案 0 :(得分:1)
让我们考虑以下API:
[HttpPost]
[Route("api/Test")]
public async Task<string> Test([FromUri]int value)
{
var result = "Done";
if (value > 5)
result = "Well Done";
return await Task.FromResult(result);
}
它可以如下调用,并且可以按预期工作:
http://<ServerUrl>/api/Test?value=10
您期望的是:
public async Task<string> Test([FromBody]int value)
这将不起作用,因为"value":10
是无效的Json并且有效的Json是{"value":10}
,这仅意味着value
必须包含在这样的类中才能使用< / p>
我们可以进行一些更改以实现您的期望,让我们将api保持为:
public async Task<string> Test([FromBody]int value)
邮寄电话为:
http://<ServerUrl>/api/Test
在调用的正文中,您只需传递10 or 15
或您想要填充参数的任何值,因为它是有效的Json或万一数组,它将是[10,15,20]
,可以是收集到([FromBody]int[] value)
唯一的缺点是,由于没有根/容器对象,因此您不能在主体中传递多个值
使用以下客户端调用API并获取结果:
async Task Main()
{
// Input Value
int input = 100;
// Json Serialize the Input
string jsonInput = JsonConvert.SerializeObject(input);
// Execute Api call Async
var httpResponseMessage = await MakeApiCall(jsonInput,
"api/Test","http://localhost:59728/");
// Process string[] and Fetch final result
var result = await FetchJsonResult<string>(httpResponseMessage);
// Print Result
result.Dump();
}
private async Task<HttpResponseMessage> MakeApiCall(string jsonInput,
string api,
string host)
{
// Create HttpClient
var client = new HttpClient { BaseAddress = new Uri(host) };
// Assign default header (Json Serialization)
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Add String Content
var stringContent = new StringContent(jsonInput);
// Assign Content Type Header
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Make an API call and receive HttpResponseMessage
HttpResponseMessage responseMessage;
responseMessage = await client.PostAsync(api, stringContent);
return responseMessage;
}
private async Task<T> FetchJsonResult<T>(HttpResponseMessage result)
{
// Convert the HttpResponseMessage to Byte[]
var resultArray = await result.Content.ReadAsStringAsync();
// Deserialize the Json string into type using JsonConvert
var final = JsonConvert.DeserializeObject<T>(resultArray);
return final;
}