簡體   English   中英

HttpClient PutAsync不向api發送參數

[英]HttpClient PutAsync doesn't send a parameter to api

在控制器上Put如下:

[HttpPut]
[ActionName("putname")]
public JsonResult putname(string name)
{
    var response = ...
    return Json(response);  
}

問題在於通過以下方式消費此API

using (httpClient = new HttpClient())
{
    string name = "abc";
    string jsonString = JsonConvert.SerializeObject(name);
    var requestUrl = new Uri("http:...../controller/putname/");
    using (HttpContent httpContent = new StringContent(jsonString))
    {
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
    }

此代碼不會將參數名稱傳遞給控制器​​。 我甚至嘗試將uri更改為/ putname /“+ name。

這對我有用:

var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");            
var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent);
Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);

和我的行動方法:

public void PutRate(AppRating model)
{
   if (model == null)
      throw new HttpResponseException(HttpStatusCode.BadRequest);

   if (ModelState.IsValid)
   {
     // ..
   }      
}

和模型

public class AppRating
{
    public int AppId { get; set; }
    public int PlatformId { get; set; }
    public decimal Rating { get; set; }
} 

-Stan

對我而言,它工作正常:

            string requestUrl = endpointUri + "/Files/";
            var jsonString = JsonConvert.SerializeObject(new { name = "newFile.txt", type = "File" }); 

            HttpContent httpContent = new StringContent(jsonString);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json");          

            HttpClient hc = new HttpClient();

            //add the header with the access token
            hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

            //make the put request
            HttpResponseMessage hrm = (await hc.PostAsync(requestUrl, httpContent));

            if (hrm.IsSuccessStatusCode)
            {
               //stuff
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM