[英]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.