Put请求返回BadRequest。获取,删除和发布工作没有错误

时间:2016-11-30 13:41:44

标签: asp.net rest request put

这是发出请求的页面



         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"
});




这是控制器



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;
        }
    }
}
&#13;
&#13;
&#13;

只有put请求失败并返回400错误请求错误。其他人使用普通的200次成功代码

我尝试了一切可能,包括使用fiddler来分析错误。我可以在更明亮的地方打开网址,并可以看到我在ajax中格式化的所有数据。

这是webconfig文件

&#13;
&#13;
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>
&#13;
&#13;
&#13;

此致

1 个答案:

答案 0 :(得分:0)

请检查您的Asp.NET webapi项目中是否有以下配置条目。您必须删除WebDAv和WebDAVModule以允许PUT和DELETE。

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

如果仍然无效,请通过IIS管理器中的Handler Mappings验证是否允许PUT动词。查找ExtensionlessUrlHandler-Integrated-4.0,双击打开它。下一步单击“请求限制”按钮并选中“动词”选项卡,如果缺少则添加PUT或选择“允许所有动词”。

<强>更新

将PUT调用的客户端代码修改为此

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
        });
    }