1

您好我正在尝试删除记录(HttpDelete)。控制器中的方法未触发并出现 405 Method Not Allowed 错误。

下面的jquery

 function deleteContract(contractId) {
            var contract = new Object();
            contract.ContractID = "ContractId";
            $.ajax({
                async: true,
                type: 'DELETE',
                data: contract,
                dataType: "json",
                url: 'http://localhost:4233/api/Contract/DeleteContractById/' + contractId,
            }).done(function (data, textStatus, xhr) {
               alert("deleted successfully")
            }).error(function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR.responseText || textStatus);
            })
        }

下面的控制器

 // DELETE: api/Contract/5
    [ResponseType(typeof(Contract))]
    [AllowAnonymous]
    [HttpDelete]
    [ActionName("DeleteContractById")]
    //[Route("api/Contract/{id}")]
    [AcceptVerbs("DELETE")]
    public HttpResponseMessage DeleteContract(Guid id)
    {
        Contract contract = db.Contract.Find(id);
        if (contract == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        db.Strata.Remove(contract);
        db.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.OK, contract);
    }

下面的 webapiconfig

public static void Register(HttpConfiguration config)
    {
                config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

                config.MapHttpAttributeRoutes();

           config.Routes.MapHttpRoute(
           name: "ControllerAndAction",
           routeTemplate: "api/{controller}/{action}/{id}",
           defaults: new { action = "GET", id = RouteParameter.Optional }
       );

    }

网页配置如下

 <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>

  <handlers>
    <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
   <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
  </customHeaders>
</httpProtocol>
    </system.webServer>

当我使用提琴手拨打电话时,它工作正常。如果我错过了代码中的任何设置,请告诉我。

感谢开发

4

3 回答 3

0

当我使用的方法不是 API 所期望的时,我得到了 405。我确实注意到了一些事情,尽管我不确定这些是潜在的问题:

  1. API 上的操作名称拼写错误,应该是 DeleteContractById(它有合同代替合同)。
  2. deleteContract 函数正在传递一个正文。API 方法不需要正文(数据)。
  3. 路由设置为期望 GUID id。传递给 deleteContract 的 ContractId 的值是否是有效的 GUID?
于 2016-06-23T05:14:53.563 回答
0

我们通过以下更改找到了解决方案

网络配置

<customHeaders>
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Access-Control-Request-Headers" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>

启动.Auth.cs

在班级级别声明以下内容

[EnableCors(origins: "http://localhost:49369", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public void ConfigureAuth(IAppBuilder app)
{
    app.UseCors(CorsOptions.AllowAll); // newly added this require to "Install-Package Microsoft.Owin.Cors"
}

控制器

[EnableCors(origins: "http://localhost:49369", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public class ContractController : ApiController
{
}

WebApi.config

public static class WebApiConfig
{

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        // Controllers with Actions
        // To handle routes like `/api/VTRouting/route`
        config.Routes.MapHttpRoute(
            name: "ControllerAndAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "GET", id = RouteParameter.Optional }
        );

    }  
}

这就是它开始工作的一切。

于 2016-06-23T10:28:56.150 回答
0

您是否尝试过使用异步语法?喜欢

public async Task<HttpResponseMessage> DeleteStrata(Guid id)
...
await db.SaveChangesAsync()
于 2016-06-22T14:42:41.180 回答