405 Error – The requested resource does not support http method ‘PUT’

While using a PUT request against a Web API call to insert a record into the database, I ran into the 405 error, “The requested resource does not support http method ‘PUT'”. I found a useful link on Stack Overflow that led me to the solution. Here is what worked for me, but I’ll first start by showing the basic call that didn’t work:

    public class ScottController : ApiController {
        public void Put([FromBody]DTO item) {
           ScottRepository.CreateItem(item);
        }
    }

The DTO class holds the fields of the object that I am trying to insert:

        public class DTO {
            public string ID { get; set; }
            public string Name { get; set; }
            public DTO() { }
        }

Those alone were not working. To get the PUT request running, I modified the controller class, adding a RoutePrefix attribute to reference the name that my jQuery call would be using, then added a Route attribute on the PUT request. Here is my final result:

    [RoutePrefix("api/Scott")]
    public class ScottController : ApiController {
        [Route]
        public void Put([FromBody]DTO item) {
           ScottRepository.CreateItem(item);
        }
    }

In case you are curious, here is my jQuery code to call Web API:

      var item = { ID: 'ABC123', Name: 'Bill'};
      $.ajax({
            url: 'http://www.bla.com/api/Scott',
            type: 'PUT',
            dataType: 'json',
            cache: false,
            contentType: "application/json",
            data: JSON.stringify(item),
            success: function (d) {
                // woohoo!                },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('sadness');
            }
      });
Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: