我有webforms asp和web api。在Web表单中,我尝试以这种方式发送到类的web api对象:
HttpClient client = HttpClientHeader("", login, ClassMd5Calc.CalculateMd5Hash(password));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
UserTariff userTariff = new UserTariff();
userTariff.Login = "some value";
userTariff.Password = "some value";
userTariff.TariffName = "some value";
var json = new JavaScriptSerializer().Serialize(userTariff);
StringContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
HttpResponseMessage response = client.PostAsync("api/ChangeTariff/", content).Result;
这是我的类(存在于数据合同解决方案中,因此两个项目都使用此类)。
[Serializable]
public class UserTariff
{
public String Login { get; set; }
public String Password { get; set; }
public String TariffName { get; set; }
public decimal Balance { get; set; }
}
我的网络API接收包,但所有字段都为空。怎么了?它是如何解决的?
public class ChangeTariffController : ApiController
{
public void Post([FromBody] UserTariff mes)
{
//mes exist, but his property are null: mes.Login=null; mes.Password=null and e.t.c. but need value: "some value"
更新1。
我也尝试了这段代码,但它显示了同样的错误:
var content = new ObjectContent<UserTariff>(new UserTariff(), new JsonMediaTypeFormatter());
content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
HttpResponseMessage response = client.PostAsync("api/ChangeTariff/", content).Result;
答案 0 :(得分:0)
您可以设置对象内容而不是字符串内容,并且应该使用json媒体类型格式化程序。这应该修复web api中的空绑定变量。
另外,使用newton soft json lib将对象转换为json。