c# - 在 PostAsync 中传递整数参数
问题描述
有一个 Get 方法,我正在尝试将其更改为 Post
[HttpGet]
public IHttpActionResult Expiry(int id)
{
return Ok(_socialChorusService.Expiry(id));
}
Get方法改为Post
[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;
但我想传递一个整数。是否有可能或者只是字符串可以在正文中传递?
任何建议,将不胜感激 ,
提前致谢
解决方案
让我们考虑以下 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
is 无效 Json 和有效 Json is {"value":10}
,这只是意味着value
需要包含在一个类中才能像这样使用
编辑1:
我们可以进行一些更改以实现您所期望的,让我们将 api 保留为:
public async Task<string> Test([FromBody]int value)
邮政电话将是:
http://<ServerUrl>/api/Test
在调用的正文中,您只需传递10 or 15
或您想要填写参数的任何值,因为这是一个有效的 Json 或者如果它是数组[10,15,20]
,可以收集到([FromBody]int[] value)
唯一的缺点是,您不能因此在 Body 中传递多个值,因为没有根/容器对象
编辑2:
使用以下客户端调用 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;
}
推荐阅读
- python - 如何在 Python 中限制 fstring 中的位数
- android - 我无法通过带有 android studio 的 FCM 发送推送通知
- asp.net - 在哪里可以查看错误 Azure“发生错误”的日志或详细信息。用于 Azure 上的 API 调用?
- python - 如何在附加数据中插入字母?
- c++ - 为什么 std::fetch_add 返回旧值?
- linux - 通过 Ray 配置在 AWS EC2 集群中的节点上禁用超线程
- node.js - Node JS 和 node-firebird 一个事务中的多个查询
- javascript - 映射数组以设置空元素
- java - Java newSingleThreadExecutor 似乎创建了很多线程
- python-3.x - 无法在 PyQt5 中的网格上创建表