0

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!

2
  • 2
    play with Fiddler proxy. it will help you to debug things like this. Commented Nov 9, 2020 at 9:14
  • This is probably due to sending wrong type of http request. Please check are you using GET or PUT. For best control of sending requests you should use Postman or something like that... Commented Nov 9, 2020 at 9:32

2 Answers 2

1

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
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try adding [FromBody] attribute before ClassA:

[HttpPut]
[Route("{primaryKey}")]
public async Task<ActionResult<ResponseSingleX<ClassA>>> Update(Guid primaryKey, [FromBody] ClassA classA)
{
    // Update database
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.