简体   繁体   中英

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 small custom cms.

Anyway, to view a page in the client, I do this:

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);
}

And it works, I get the actual page data from the API, however the PUT method in the client is not working, this is it:

[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());
}

When I submit the form for the above method it just redirects to the previous request but the changes aren't saved.

Here's the put method from the api:

[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();
}

When I inspect using breakpoints, I can see that the response in the POST method says 415 unsupported media type

The 415 unsupported media type status code means that

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

When you use new StringContent(page.ToString()) then the media type for the StringContent created defaults to text/plain.

You need to send content in json format:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM