我正在构建一个应该将数据发布到WebApi的控制台应用程序,我使用Postman测试了Api,并且它正在运行。现在我在控制台应用程序中构建C#代码,但我无法使其工作,因为它总是返回Http错误代码415.
我的邮差配置: 请不要介意错误400,因为那是因为我的DateTime格式不正确。正确的格式化一切都成功。
这是我发布到WebApi的代码:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:52277/");
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LoginResponse.access_token);
StringContent parameterContent = new StringContent(HttpUtility.UrlEncode("pssltl=0000000015340882"));
HttpResponseMessage response = await client.PostAsync("api/PutData", parameterContent);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
// EDIT 我的API控制器:
//POST api/PutData
[Route("PutData")]
[HttpPost]
//Authorize nodig voor deze handeling
[Authorize]
public IHttpActionResult PutData(TijdRegistratieModel trm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (trm == null)
{
return BadRequest("Geen data ingestuurd!");
}
_repo.InsertTijdregistratie(trm.pssltl, trm.Start);
return Ok(trm);
}
TijdsRegistratieModel:
public class TijdRegistratieModel
{
[Required]
public string pssltl { get; set; }
public DateTime Start { get; set; }
}