C# Web API 2 - AJAX Request for PUT method returning 405 (Method Not Allowed)

Asked

Viewed 141 times

0

Good morning! I am building a system using C# as back and React on the front, and I have a problem in two controllers (supposedly), but the error seems to be the same, and whenever I make an AJAX request with the method of the kind PUT, get the error

PUT http://localhost:49232/api/Product/1025 405 (Method Not Allowed)

Followed by

{Message: "The requested Resource does not support http method 'PUT'."}

I read about CORS, I made the recommended adjustments on several topics, but the error remains. Follow the code :

$.ajax({
  url: URL,//A URL é montada acima, e para teste seu valor é http://localhost:49232/api/Products/1025
  contentType: 'application/json',
  dataType: 'JSON',
  data: { "product": json}, //Aqui passo o objeto montado
  type: 'PUT',
  beforeSend: function () {

  },
  success: function (response) {
    // do something
  }.bind(this),
  error: function (response) {
    // do something else
  }

});

Action C#:

[ResponseType(typeof(void))]
    public async Task<IHttpActionResult> PutProduct(int id, Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != product.IdProduct)
        {
            return BadRequest();
        }

        db.Entry(product).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

If you can help me, gratitude.

  • Add: [Httpput], after '[Responsetype(typeof(void))]'.

  • @I did it, but it didn’t work.

1 answer

3

Ricardo, can your URL be solved? I didn’t run a table test here but your example uses the URL

http://localhost:49232/api/Products/1025

And your method is waiting for two arguments (an integer and an object) and is named Putproduct and not Products.

  • Angelo, thank you for your contribution. The URL is being resolved yes. Actually I’ve already "solved" the problem - it wasn’t a solution at all, but it worked - simply by deleting the controller and recreating it. I don’t know what was wrong, but now it works.

  • Imagine! This may be a reference bug or a letter you weren’t seeing that was wrong (it happens a lot with me rs).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.