405方法不允许-ASP.NET Web API

BSB*_*BSB 5 c# http-headers asp.net-web-api asp.net-web-api-routing

我已经在Google和StackOverflow上检查了ASP.NET Web API中不允许的405方法的所有答案,并且所有解决方案均无效。

  1. 已检查的CORS
  2. 已检查的WebDAV
  3. 检查HTTPDelete属性

我正在创建一个ASP.NET Web API,并且有2个虚拟控制器。

我能够对一个控制器而不是另一个控制器使用HTTP Delete方法。

价值控制者

using System.Collections.Generic;
using System.Web.Http;

namespace JobSite_WebAPI.Controllers
{
  public class ValuesController : ApiController
  {
    List<string> strings = new List<string>()
    {
        "value1", "value2","value3"
    };
    // GET api/values
    public IEnumerable<string> Get()
    {
        return  strings;
    }

    // GET api/values/5
    public string Get(int id)
    {
        return strings[id];
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
        strings.RemoveAt(id);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

职位详情控制器

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Web.Http;
 using DataAccess;

 namespace JobSite_WebAPI.Controllers
 {
  public class JobDetailController : ApiController
  {
    public JobDetailController()
    {
        JobSiteEntities entities = new JobSiteEntities();
        entities.Configuration.ProxyCreationEnabled = false;
    }
    public IEnumerable<JobDetail>Get()
    {
        using (JobSiteEntities entities = new JobSiteEntities())
        {
            return entities.JobDetails.ToList();
        }
    }

[HttpGet]
    public HttpResponseMessage Get(int id)
    {
        using (JobSiteEntities entities = new JobSiteEntities())
        {
            var entity = entities.JobDetails.FirstOrDefault(e => e.JOBID == id);
            if (entity != null)
            {
                return Request.CreateResponse(HttpStatusCode.OK, entity);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Job With Id = " + id.ToString() + " not found");
            }
        }
    }


 [HttpGet]
    public HttpResponseMessage RetrieveJobByLocation(string locationName)
    {
        try
        {
            using (JobSiteEntities entities = new JobSiteEntities())
            {
                IEnumerable<JobDetail> jobDetails = entities.JobDetails.Where(e => e.Location.LocationName.ToLower() == locationName).ToList();

                if (jobDetails != null)
                    return Request.CreateResponse(HttpStatusCode.OK, jobDetails);
                else
                    return Request.CreateResponse(HttpStatusCode.NotFound);

            }
        }
        catch(Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
        }
    }

    [HttpDelete]
    public HttpResponseMessage Delete(int jobId)
    {
        try
        {
            using (JobSiteEntities entities = new JobSiteEntities())
            {
                var entity = entities.JobDetails.FirstOrDefault(e => e.JOBID == jobId);

                if (entity == null)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound, "Job Id with id " + jobId + "is not found");
                }
                else
                {
                    entities.JobDetails.Remove(entity);
                    entities.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            }
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
        }
    }
}

}
Run Code Online (Sandbox Code Playgroud)

WebAPIConfig.cs

 var cors = new EnableCorsAttribute("*", "*", "*");
 config.EnableCors(cors);


 // Web API routes
 config.MapHttpAttributeRoutes();

 config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
Run Code Online (Sandbox Code Playgroud)

Web配置

 <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" />
Run Code Online (Sandbox Code Playgroud)

我启用了CORS,禁用了WebDAV。还为删除方法添加了HTTPDelete属性。

面临的问题是,值控制器的删除方法在Fiddler中工作正常,但对于JobDetails控制器,我不允许使用405方法。

我能够执行GET和POST Method.Am也遇到相同的问题。

添加了来自提琴手的错误消息屏幕截图。 Fiddler URL Fiddler错误消息

Nko*_*osi 5

它之所以有效,ValuesController是因为基于约定的路由模板......

"api/{controller}/{id}" 
Run Code Online (Sandbox Code Playgroud)

{id}占位符,控制器符合该占位符,但JobDetailController.Delete(int jobId)由于参数名称与路由模板不匹配jobId。将这些参数参数更改为 ,int id以使其与约定设置的路由模板相匹配。

[HttpDelete]
public HttpResponseMessage Delete(int id) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

否则,您可以使用属性路由,因为它也可以通过以下方式启用config.MapHttpAttributeRoutes()

参考:ASP.NET Web API 2 中的属性路由

[RoutePrefix("api/JobDetail")] 
public class JobDetailController : ApiController {

    [HttpGet]
    [Route("")] //Matches GET api/jobdetail
    public IEnumerable<JobDetail> Get() {
        //...
    }

    [HttpGet]
    [Route("{id:int}")] //Matches GET api/jobdetail/1
    public HttpResponseMessage Get(int id) {
       //...
    }

    [HttpGet]
    [Route("{locationName}")] //Matches GET api/jobdetail/somewhere
    public HttpResponseMessage RetrieveJobByLocation(string locationName) {
        //...
    }

    [HttpDelete]
    [Route("{jobId:int}")] //Matches DELETE api/jobdetail/1
    public HttpResponseMessage Delete(int jobId) {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,当路由到控制器时,它要么按照约定,要么按照属性,而不是两者兼而有之。如果按属性路由到操作,则控制器上的所有其他操作也需要属性路由。