[英]HttpClient {StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'
[英]httpClient.PutAsync() not updating, 415 Unsupported media type
I am building a Rest API
and a Rest Client
, the api url is https://localhost:44341
and the client url is https://localhost:44305/
, specifically I want to be able to edit pages in the client for a小型定制厘米。
无论如何,要在客户端查看页面,我这样做:
public async Task<IActionResult> Edit(long id)
{
Page page = new Page();
using (var httpClient = new HttpClient())
{
using var response = await httpClient.GetAsync("https://localhost:44341/api/Pages/" + id);
string apiResponse = await response.Content.ReadAsStringAsync();
page = JsonConvert.DeserializeObject<Page>(apiResponse);
}
return View(page);
}
它有效,我从 API 获取实际页面数据,但是客户端中的 PUT 方法不起作用,就是这样:
[HttpPost]
public async Task<IActionResult> Edit(Page page)
{
using (var httpClient = new HttpClient())
{
using var response = await httpClient.PutAsync("https://localhost:44341/api/Pages/" +
page.Id, new StringContent(page.ToString()));
string apiResponse = await response.Content.ReadAsStringAsync();
}
return Redirect(Request.Headers["Referer"].ToString());
}
当我为上述方法提交表单时,它只是重定向到上一个请求,但不会保存更改。
这是 api 中的put
方法:
[HttpPut("{id}")]
public async Task<ActionResult> PutPage(long id, Page page)
{
if (id != page.Id)
{
return BadRequest();
}
context.Entry(page).State = EntityState.Modified;
await context.SaveChangesAsync();
return NoContent();
}
当我使用断点进行检查时,我可以看到POST
方法中的response
显示415 unsupported media type
415 unsupported media type
状态码意味着
服务器拒绝为请求提供服务,因为请求的实体采用所请求方法的请求资源不支持的格式。
当您使用new StringContent(page.ToString())
时,创建的StringContent的媒体类型默认为 text/plain。
您需要以 json 格式发送内容:
var content = new StringContent(JsonConvert.SerializeObject(page, Encoding.UTF8, "application/json");
using var response = await httpClient.PutAsync($"https://localhost:44341/api/Pages/{page.Id}", content);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.