Web API的删除操作方法未被触发。

3
我在我的项目中有一个Web API控制器,如下所示:
public class EmployeeController : ApiController
{
    static readonly IEmployeeRepository repository = new EmployeeRepository();
    // GET api/<controller>
    [HttpGet]
    public object Get()
    {
        var queryString = HttpContext.Current.Request.QueryString;
        var data = repository.GetAll().ToList();
        return new { Items = data, Count = data.Count() };
    }

    public Employee GetEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return emp;
    }

    // POST api/<controller>
    public HttpResponseMessage PostEmployee(Employee emp)
    {
        emp = repository.Add(emp);
        var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

        string uri = Url.Link("Employee", new { id = emp.EmployeeID });
        response.Headers.Location = new Uri(uri);
        return response;
    }
     [HttpPut]
    // PUT api/<controller>
    public void PutEmployee(Employee emp)
    {

        if (!repository.Update(emp))
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
    [HttpDelete]
     public void DeleteEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        repository.Remove(id);
    }
}

对于我来说,get和post方法被正确触发了。

但是,删除方法没有被触发。

我的Webapicongif.cs文件如下:

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

并将global.cs文件修改如下

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);



    }

曾经我对员工进行了删除操作

General:

Request URL:http://localhost:63187/api/Employee/2
Request Method:DELETE
Status Code:404 Not Found
Remote Address:[::1]:63187

响应头

   Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Cache-Control:no-cache
Content-Length:204
Content-Type:application/json; charset=utf-8
Date:Thu, 30 Mar 2017 12:00:21 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU2FtcGxlXE1WQ1xEYXRhTWFuYWdlclxBZGFwdG9yc1xTYW1wbGVcYXBpXEVtcGxveWVlXDI=?=

请求头

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:1
Content-Type:application/json; charset=UTF-8
DataServiceVersion:2.0
Host:localhost:63187
MaxDataServiceVersion:2.0
Origin:http://localhost:63187
Referer:http://localhost:63187/CRUDRemote/Remove
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest

请求主体

2

我的ajax请求如下:

beforeSend:function (),
contentType:"application/json; charset=utf-8",
data:"2",
error:function (e),
success:function (),
type:"DELETE",
url:"/api/Employee/2",

我在哪里犯了错误?


看一下这里,看看它是否可以解决你的问题。 可能是同样的问题 - Jack M
1
你是从哪里调用API的,MVC应用程序还是Ajax请求? - Sulay Shah
可能是托管应用程序的Web服务器不支持该方法吗? - Phil Cooper
请指定您的服务托管在哪个服务器上。IIS?自托管? - Nameless
嗨,Sulay,我从Ajax请求中打来了电话。 - Kalai
3个回答

0
在托管在IIS下的新WebAPI项目中,PUT和DELETE方法默认会返回404错误。在使用它们之前,必须编辑IIS的applicationhost.config文件。

%userprofile%\documents\iisexpress\config\applicationhost.config

搜索

<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

and replace it by

<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

此外,正如stackoverflow答案所建议的那样,您还需要在同一文件中注释掉以下行。

<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" /> 
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />

0

对我来说,在web.config中添加以下内容总是有效的。默认情况下,在远程服务器上使用WebAPI时不允许删除。

   <system.webServer>
    <modules>
    <remove name="WebDAVModule"/>
    </modules>
    <handlers>
    <remove name="WebDAV" />
    <remove name="ExtensionlessUrl-Integrated-4.0" />
    <add name="ExtensionlessUrl-Integrated-4.0"
    path="*."
    verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
    type="System.Web.Handlers.TransferRequestHandler"
    preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    </system.webServer>

0
最后我找到了问题,是在Global.cs和WebApiConfig中犯了错误。
更新了Global.cs文件。
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        //GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);


    //    WebApiConfig.Register(GlobalConfiguration.Configuration);
    }

和WebApiConfig

     public static void Register(HttpConfiguration config)
    {
        //config.MapHttpAttributeRoutes();

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

现在,已触发更新的删除操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接