1

Hi i am trying to delete the record (HttpDelete).the method in the controller is not triggering and getting 405 Method Not Allowed error.

jquery below

 function deleteContract(contractId) {
            var contract = new Object();
            contract.ContractID = "ContractId";
            $.ajax({
                async: true,
                type: 'DELETE',
                data: contract,
                dataType: "json",
                url: 'http://localhost:4233/api/Contract/DeleteContractById/' + contractId,
            }).done(function (data, textStatus, xhr) {
               alert("deleted successfully")
            }).error(function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR.responseText || textStatus);
            })
        }

controller below

 // DELETE: api/Contract/5
    [ResponseType(typeof(Contract))]
    [AllowAnonymous]
    [HttpDelete]
    [ActionName("DeleteContractById")]
    //[Route("api/Contract/{id}")]
    [AcceptVerbs("DELETE")]
    public HttpResponseMessage DeleteContract(Guid id)
    {
        Contract contract = db.Contract.Find(id);
        if (contract == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        db.Strata.Remove(contract);
        db.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.OK, contract);
    }

webapiconfig below

public static void Register(HttpConfiguration config)
    {
                config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

                config.MapHttpAttributeRoutes();

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

    }

web config below

 <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>

  <handlers>
    <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" />
    </handlers>
   <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
  </customHeaders>
</httpProtocol>
    </system.webServer>

when i make the call using fiddler its working fine. let me know if i have missed out any settings in the code.

Thanks Dev

Devanathan.S
  • 1,072
  • 1
  • 12
  • 19
  • 1
    Possible duplicate of [ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8](http://stackoverflow.com/questions/10906411/asp-net-web-api-put-delete-verbs-not-allowed-iis-8) – Luke Jun 22 '16 at 14:40
  • Please take a look at these existing questions: http://stackoverflow.com/questions/10906411/asp-net-web-api-put-delete-verbs-not-allowed-iis-8 http://stackoverflow.com/questions/15619075/webapi-delete-not-working-405-method-not-allowed http://stackoverflow.com/questions/10906411/asp-net-web-api-put-delete-verbs-not-allowed-iis-8 – Luke Jun 22 '16 at 14:41
  • I have had this issue before and I _disabled_ WebDav for the application pool that my website was hosted on. – Luke Jun 22 '16 at 14:47
  • please look athttps://stackoverflow.com/a/55134621/4746570 – BehrouzMoslem Mar 13 '19 at 14:25

3 Answers3

0

Have you tried to use async syntax? Like

public async Task<HttpResponseMessage> DeleteStrata(Guid id)
...
await db.SaveChangesAsync()
pacholik
  • 7,596
  • 8
  • 43
  • 50
Igor Krein
  • 117
  • 1
  • 7
  • 1
    Welcome to Stack Overflow! Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See [answer] for more information. – Heretic Monkey Jun 22 '16 at 14:44
  • 1
    The error is a 405 Method Not Allowed. The server is actively refusing the connection. Sadly changing it to Async won't solve this issue to allow the server to accept the HTTP request using the DELETE HTTP verb. – Luke Jun 22 '16 at 14:44
  • Sorry for a late response. Think, my suggestion was a not well-thought. Now I don't think it would help. The problem lies somewhere else and I don't know where. Sorry. – Igor Krein Jun 30 '16 at 06:25
0

I've gotten 405's when the method I was using was not what the API was expecting. And I did notice a few things though I'm not sure these are the underlying problems:

  1. The action name on the API is misspelled, it should be DeleteContractById (it has contract in place of contract).
  2. The deleteContract function is passing a body. The API method does not expect a body (data).
  3. The route is setup to expect a GUID id. Is the value of ContractId passed into deleteContract a valid GUID?
Jeff Siver
  • 7,201
  • 27
  • 32
0

We have found the solution by doing below changes

web.config

<customHeaders>
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Access-Control-Request-Headers" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>

Startup.Auth.cs

Declare the below in class level

[EnableCors(origins: "http://localhost:49369", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public void ConfigureAuth(IAppBuilder app)
{
    app.UseCors(CorsOptions.AllowAll); // newly added this require to "Install-Package Microsoft.Owin.Cors"
}

Controller

[EnableCors(origins: "http://localhost:49369", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public class ContractController : ApiController
{
}

WebApi.config

public static class WebApiConfig
{

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        // Controllers with Actions
        // To handle routes like `/api/VTRouting/route`
        config.Routes.MapHttpRoute(
            name: "ControllerAndAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "GET", id = RouteParameter.Optional }
        );

    }  
}

That's all it started working.

Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294
Devanathan.S
  • 1,072
  • 1
  • 12
  • 19
  • I take it that you're accepting GET, POST, PUT, DELETE, OPTIONS requests from other domains if you're enabling CORS? If you're not, then I don't think you should be enabling it. – Luke Jun 29 '16 at 14:29