0

I am trying to PUT an update to a user using JSON to ASP.NET Web API via JQuery's Ajax function. I keep getting a 405 (Method not Allowed) response from the server. I have tried just about everything, including disabling the WebDAV module in web.config and adding Access-Control-Allow-Origin headers to my web.config as well.

I used the database-first approach using ADO Model and DbContext generation. The controllers were also generated by ASP.NET upon creation. I assume they should work.

I have tried both PUT and POST to no avail. I have no idea what I am doing wrong.

My JS code:

function UpdateUserLoginTime(user) {

   $.getScript("src/js/datetimeutils.js");
   var url = "http://foo.bar.com:8081/api/user/".concat(user.ID);

   var current = CurrentDateTime();

   $.ajax({
       url: url,
       type: 'PUT',
       data: JSON.stringify({"LastLoginDate" : current}),
       datatype: "json",
       contentType: "application/json; charset=utf-8",
       crossDomain: true,
       success: function (data) {
           alert('User login time updated sucessfully');
       },
       error: function () {
           alert('Update login time error');
       }
   });
}

For the post, I tried JSON.stringify(user) as well (without concat(ID) on url).

Here is my ASP.NET Controller code:

 // PUT api/User/5
    public HttpResponseMessage PutUser(string id, User user)
    {
        if (ModelState.IsValid && id == user.ID)
        {
            db.Entry(user).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

    // POST api/User
    public HttpResponseMessage PostUser(User user)
    {
        if (ModelState.IsValid)
        {
            db.Users.Add(user);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.CAC }));
            return response;
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

My config:

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
</modules>
<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>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

My RouteConfig:

 public class RouteConfig
{
    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 }
        );
    }
}
Logan B. Lehman
  • 4,867
  • 7
  • 32
  • 45

1 Answers1

0

You need enable CORS for web api, else when send a request, you always get response 405 not allow. Look this.

Zack Yang
  • 399
  • 2
  • 11