3

I have a web api controller in my project, as follows

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);
    }
}

For me, get and post method getting triggered correctly

But, Delete Method is not getting triggered.

and my 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();
    }

and the global.cs file as follows

    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);



    }

once i did the delete to the Employee

General:

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

Response Headers

   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=?=

Request Headers

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

Request Payload

2

my ajax request will as below

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

Where i committing my mistake

Kalai
  • 287
  • 1
  • 5
  • 17

3 Answers3

0

In the new WebAPI project hosted under IIS, PUT and DELETE methods return 404 errors out of the box. applicationhost.config of IIS has to be edited before you use them.

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

Search for

<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" />

and in addition to this as this stackoverflow answer suggests, you have to comment out the following lines in the same file.

<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" />
Community
  • 1
  • 1
Nameless
  • 1,026
  • 15
  • 28
0

For me adding the following in web.config worked all the time.By default delete is not allowed when using WebAPI on remote server.

   <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>
ashish
  • 2,028
  • 1
  • 10
  • 6
0

At last i found the issue, i have done the mistake in Global.cs and WebApiConfig

Updated Global.cs filed

    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);
    }

and 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();
    }

Now, the Delete action updated triggered.

Kalai
  • 287
  • 1
  • 5
  • 17