通过HttpClient发送对象

时间:2016-11-11 11:56:27

标签: c# asp.net-mvc asp.net-web-api2 httpclient

我尝试通过HTTP方法访问以下WebAPI控制器方法

create

这是我尝试使用send [System.Web.Http.Route("api/Users/Signin")] [ResponseType(typeof(bool))] public bool UserSingIn(User obj) { bool isuserexit = _usersRepo.UserSignIn(obj); if (isuserexit == true) { return true; } return false; } 对象的HTTP方法,

User obj

但这是以 private string USER_URL = "http://localhost:3623/api/Users"; public bool GetUser(User obj) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(USER_URL); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PutAsJsonAsync("Users/Signin", obj).Result; if (response.IsSuccessStatusCode) return response.Content.ReadAsAsync<bool>().Result; return false; } catch { return false; } }

结尾

2 个答案:

答案 0 :(得分:0)

您的Web API默认只处理GET请求。如果要使用HttpPut属性,则需要使用[HttpPut] [System.Web.Http.Route("api/Users/Signin")] [ResponseType(typeof(bool))] public bool UserSingIn(User obj) 属性对其进行修饰。

$(document).ready(function() {
  $("#select").on("change", function() {
    $('.result').html('');
    
    $(".colors").each(function() {
      var color = $(this).attr('title');
      $(".result").append("<div>" + color + "</div>");
    });
  });
});

答案 1 :(得分:0)

您可以使用postAsync方法。

var data = JsonConvert.SerializeObject(dataToSave);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var resp = client.PostAsync(apiUrl, content).Result;