首页 > 解决方案 > 在 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;

但我想传递一个整数。是否有可能或者只是字符串可以在正文中传递?

任何建议,将不胜感激 ,

提前致谢

标签: c#httppostheaderhttp-headers

解决方案


让我们考虑以下 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":10is 无效 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;
}

推荐阅读