16

I have a VS2012 MVC4 solution where I test Web API Controllers.

I successfully tested the GET, POST, PUT but the DELETE still got me an http 404 error. When I set a breakpoint in my 'DeleteMovie' action in my api controller, the breakpoint is never reached.

I read a lot of posts about this problem but no one helped me.

Here is my API Controller for the DELETE:

    [HttpDelete]
    public HttpResponseMessage DeleteMovie(int id)
    {    
        // Delete the movie from the database     
        // Return status code    
        return new HttpResponseMessage(HttpStatusCode.NoContent);

    }

Here is my html page:

<script type="text/javascript">

    deleteMovie(1, function ()
    {
        alert("Movie deleted!");
    });

    function deleteMovie(id, callback) {
        $.ajax({
            url: "/api/Movie",
            data: JSON.stringify({ id: id }),
            type: "DELETE",
            contentType: "application/json;charset=utf-8",
            statusCode: {
                204: function () {
                    callback();
                }
            }
        });
    }

</script>

My classic route is as follow:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

My routing for API is as follow:

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "ActionApi", 
            routeTemplate: "api/{controller}/{action}/{id}", 
            defaults: new { id = RouteParameter.Optional }
        );

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

In my solution properties, I configure the 'Use local IIS Web server' with 'Use IIS Express' checked

I also tried with 'Use Visual Studio Development Server' but same problem.

Any idea?

Thanks.

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • In your browser, if you use the debug tools, can you capture the URL that actually gets emitted by jQuery and see if it looks sane ? – Russ Clarke Feb 28 '13 at 12:08

4 Answers4

47

If the error you are receiving is an html content type from IIS, error 404.0

Make sure you have the section in your web.config that is added by the Web Api template. By default IIS will not serve the DELETE verb, and this config overrides the behavior.

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
Russell Chadwick
  • 471
  • 1
  • 3
  • 3
  • 1
    +1 I started with an MVC project but only wanting it for WebAPI. So after removing what I thought was MVC specific config, my DELETE requests were 404ing. Thanks. – Luke Baulch May 30 '13 at 07:31
18

HTTP DELETE does not have a body. You need to pass the id as a query string parameter.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • 1
    Thank you. You are right! I found the code on a blog post here: http://stephenwalther.com/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx So I really don't think of a such problem! – Bronzato Feb 28 '13 at 12:40
1

According to the answer by Russell I took a look in web config and found two lines in handlers method

....
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />

I've removed the last one and it worked.

Just an example of usage on client (typescript)

    public deleteComment(commentId: number) {
        var url = 'api/comments/' + commentId;
        return this.$http.delete(url);
    }

and server side

    [Route("{id:int}")]
    public async Task<IHttpActionResult> Delete(int id){
        await _snippetService.DeleteComment(id);
        return Ok();
    }
Artiom
  • 7,694
  • 3
  • 38
  • 45
1

Ran across the 404 running on Mac using Dotnet Core.

In my case I changed the attribute annotation from HttpDelete to HttpDelete("{id}")

Jason Foglia
  • 2,414
  • 3
  • 27
  • 48