Can't call delete function from Ajax jQuery to

2019-08-22 10:15发布

I'm using jQuery 3.2.1. I'm trying to call API by Ajax jQuery.

I'm following an example and code like this:

(() => {
    function delTest() {
        $.ajax({
            url: 'http://localhost:3413/api/person?ID=100',
            type: 'DELETE',
            dataType: 'json',
            data: { "": "Sourav Kayal" },
            success: function (data, textStatus, xhr) {
                console.log(data);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('Error in Operation');
            }
        });
    }
})();

and API

   public class personController : ApiController  
    {  
        [HttpDelete]  
        public string Delete([FromUri] int ID, [FromBody] String name)  
        {  
            return "Delete Operation" + "ID:- " + ID + "Name:- " + name;  
        }  
    }


protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);

        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

However, it's not working now.

Returns an error: 404 Not found

1条回答
在下西门庆
2楼-- · 2019-08-22 10:55

I am using below code and its working fine on my machine. I think you need to add method name delete in the URL, it should look like "http://localhost:3413/api/person/Delete?ID=100"

<script type="text/javascript">

        function delTest() {

        $.ajax({
            url: 'http://localhost:3413/person/Delete?ID=100',
            type: 'DELETE',
            dataType: 'json',
            data: { name: "Sourav Kayal" },
            success: function (data, textStatus, xhr) {
                console.log(data);
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('Error in Operation');
            }
        });
    }
</script> 

<input type="button" name="delete" onclick="delTest()" value="makeCall"/>

and API code:

  [System.Web.Http.HttpDelete]
        public string Delete([FromUri] int ID, [FromBody] String name)
        {
            return "Delete Operation" + "ID:- " + ID + "Name:- " + name;
        }
查看更多
登录 后发表回答