Put request returns BadRequest. Get, delete and Post work with no errors

Question

This is the page that makes the requests

         var customStore = new DevExpress.data.CustomStore({
    load: function(loadOptions) {
        return $.getJSON('/erg/api/api/Caveats');
    },
    byKey: function(key) {
        return $.getJSON('http://webcrm/erg/api/api/Caveats' + "/" + encodeURIComponent(key));
    },
    insert: function(values) {
        return $.post('http://webcrm/erg/api/api/Caveats', values);
    },
    update: function(key, values) {
        return $.ajax({
             url: 'http://webcrm/erg/api/api/Caveats' + "/" + encodeURIComponent(key),
            method: "PUT",
			data: values
        });
    },
    remove: function(key) {
        return $.ajax({
            url: 'http://webcrm/erg/api/api/Caveats' + "/" + encodeURIComponent(key),
            method: "DELETE",
        });
    },
    key: "CaveatID"
});

Here is the controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using CRMApi.Models;

namespace CRMApi.Controllers
{
    public class CaveatsController : ApiController
    {
        private CaveatEntities db = new CaveatEntities();

        // GET: api/Caveats
        public IQueryable<Caveat> GetCaveats()
        {
            return db.Caveats;
        }

        // GET: api/Caveats/5
        [ResponseType(typeof(Caveat))]
        public IHttpActionResult GetCaveat(int id)
        {
            Caveat caveat = db.Caveats.Find(id);
            if (caveat == null)
            {
                return NotFound();
            }

            return Ok(caveat);
        }

        // PUT: api/Caveats/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutCaveat(int id, Caveat caveat)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != caveat.CaveatID)
            {
                return BadRequest();
            }

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

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CaveatExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Caveats
        [ResponseType(typeof(Caveat))]
        public IHttpActionResult PostCaveat(Caveat caveat)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Caveats.Add(caveat);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = caveat.CaveatID }, caveat);
        }

        // DELETE: api/Caveats/5
        [ResponseType(typeof(Caveat))]
        public IHttpActionResult DeleteCaveat(int id)
        {
            Caveat caveat = db.Caveats.Find(id);
            if (caveat == null)
            {
                return NotFound();
            }

            db.Caveats.Remove(caveat);
            db.SaveChanges();

            return Ok(caveat);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool CaveatExists(int id)
        {
            return db.Caveats.Count(e => e.CaveatID == id) > 0;
        }
    }
}

Only the put request fails and returns a 400 bad request error. The others work well with a normal 200 succcess code

I have tried everything possible including using fiddler to analyse the error. I can open the url in the broser and can see all my data formatted in ajax.

This is the webconfig file

The wrbapi was generated using asp.net and is connecting to a sql database

    <?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-CRMApi-20161123093835.mdf;Initial Catalog=aspnet-CRMApi-20161123093835;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="CaveatEntities" connectionString="metadata=res://*/Models.Caveat.csdl|res://*/Models.Caveat.ssdl|res://*/Models.Caveat.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=192.168.16.228;initial catalog=ERGSERVER;persist security info=True;user id=sa;password=Red0ne?!123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="ERGSERVEREntities" connectionString="metadata=res://*/Controllers.SalesSupportExecutive.csdl|res://*/Controllers.SalesSupportExecutive.ssdl|res://*/Controllers.SalesSupportExecutive.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=192.168.16.228;initial catalog=ERGSERVER;persist security info=True;user id=sa;password=Red0ne?!123;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="ERGSERVEREntities1" connectionString="metadata=res://*/Models.SalesSupportExecutiveModel.csdl|res://*/Models.SalesSupportExecutiveModel.ssdl|res://*/Models.SalesSupportExecutiveModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=192.168.16.228;initial catalog=ERGSERVER;persist security info=True;user id=sa;password=Red0ne?!123;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  <add name="BacksModel" connectionString="data source=192.168.16.228;initial catalog=ERGSERVER;persist security info=True;user id=sa;password=Red0ne?!123;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings>
  <appSettings></appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <remove name="WebDAV" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="WebDAVModule" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

Regards


Show source
| rest   | asp.net   | request   | put   2016-11-30 14:11 1 Answers

Answers to Put request returns BadRequest. Get, delete and Post work with no errors ( 1 )

  1. 2016-11-30 15:11

    Please check if you have following configuration entries in your Asp.NET webapi project. You have to remove WebDAv and WebDAVModule to allow PUT and DELETE.

      <system.webServer>
        <handlers>
          <remove name="WebDAV" />
        </handlers>
        <modules runAllManagedModulesForAllRequests="true">
          <remove name="WebDAVModule" />
        </modules>
      </system.webServer>
    

    If it is still not working, then verify if PUT verb is allowed by going to Handler Mappings in your IIS Manager. Look for ExtensionlessUrlHandler-Integrated-4.0, open it by double clicking it. Next Click on Request Restrictions button and on check the Verbs tab, add PUT if it is missing or select allow all verbs.

    Update:

    Modify your client side code for PUT invoke to this

    update: function(key, values) {
            return $.ajax({
                 url: 'http://webcrm/erg/api/api/Caveats/' + encodeURIComponent(key),
                type: 'PUT',
                contentType: 'application/json; charset=utf-8',
                data: values
            });
        }
    

Leave a reply to - Put request returns BadRequest. Get, delete and Post work with no errors

◀ Go back