I have a .Net Core C# API that looks like this:
[HttpPut]
[Route("{primaryKey}")]
public async Task<ActionResult<ResponseSingleX<ClassA>>> Update(Guid primaryKey, ClassA classA)
{
// Update database
}
I try to do an update using the following code:
// Create a ClassA object and put some data in it
...
//GetServiceUrl() == return "http://localhost:9003/api/Configurations/";
serviceUrl = _shared.GetServiceUrl() + classA.PrimaryKey.ToString();
string requestBody = System.Text.Json.JsonSerializer.Serialize(classA);
HttpContent requestContent = new StringContent(requestBody, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = await client.PutAsync(serviceUrl, requestContent);
Stream responseStream = await responseMessage.Content.ReadAsStreamAsync();
responseMessage.EnsureSuccessStatusCode();
var updatedResponse = await System.Text.Json.JsonSerializer.DeserializeAsync<ResponseSingleX<ClassA>>(responseStream, _serializerOptions);
Assert.True(updatedResponse.Success);
var updatedClassA = updatedResponse.Element;
The problem I have is that responseMessage == "Method Not Allowed". Since this is literarily the first time I have ever used Rest (no matter the programming language), I am at a loss to why this does not work.
UPDATE 0: I found my mistake. See my answer for the cause of the problem. Thank you for your help!
I found my error. The class itself has an URL defined that defines additional parameters.
[Route("...") // <-This is what I missed
[ApiController]
public class SomeController
{
...
}
Try adding [FromBody] attribute before ClassA:
[HttpPut]
[Route("{primaryKey}")]
public async Task<ActionResult<ResponseSingleX<ClassA>>> Update(Guid primaryKey, [FromBody] ClassA classA)
{
// Update database
}
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.