title: MVC-Web API: 405 method not allowed
body: <p>So, I am stuck in a strange behavior, that is, I am able to send(or POST) data using <code>Postman (plugin of chrome)</code> or using <code>RESTClient(extension of Firefox)</code>, </p>
  
  <p><img src="https://i.stack.imgur.com/EQxjZ.jpg" alt="enter image description here"></p>
  
  <p>but not able to send it from my html file which lies outside the project. It shows following error when i open the html in chrome: </p>
  
  <pre><code>OPTIONS http://localhost:1176/api/user/ 405 (Method Not Allowed)
  XMLHttpRequest cannot load http://localhost:1176/api/user/. Invalid HTTP status code 405 
  </code></pre>
  
  <p>I am not able to make out why is this happening. Following are the details, you might need to help me solve my error:</p>
  
  <p><strong>UserController.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Web.Http;
  using WebAPIv2.Models;
  
  namespace WebAPIv2.Controllers
  {
      public class UserController : ApiController
      {
          static IUserRepository userRepository = new UserRepository();
  
          [HttpGet]
          public List&lt;TableUser&gt; GetAllUsers()
          {
              return userRepository.GetAll();
          }
  
          [HttpGet]
          public HttpResponseMessage GetUser(int id)
          {
              TableUser user = userRepository.Get(id);
              if (user == null)
              {
                  return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User Not found for the Given ID");
              }
  
              else
              {
                  return Request.CreateResponse(HttpStatusCode.OK, user);
              }
          }
  
          [HttpPost]
          public HttpResponseMessage PostUser(TableUser user)
          {
              user = userRepository.Add(user);
              var response = Request.CreateResponse&lt;TableUser&gt;(HttpStatusCode.Created, user);
              string uri = Url.Link("DefaultApi", new { id = user.UserId });
              response.Headers.Location = new Uri(uri);
              return response;
          }
  
          [HttpPut]
          public HttpResponseMessage PutUser(int id, TableUser user)
          {
              user.UserId = id;
              if (!userRepository.Update(user))
              {
                  return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Unable to Update the User for the Given ID");
              }
              else
              {
                  return Request.CreateResponse(HttpStatusCode.OK);
              }
          }
  
          [HttpDelete]
          public HttpResponseMessage DeleteProduct(int id)
          {
              userRepository.Remove(id);
              return new HttpResponseMessage(HttpStatusCode.NoContent);
          }
      }
  }
  </code></pre>
  
  <p><strong>User.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  
  namespace WebAPIv2.Models
  {
      public class User
      {
          public int UserId { get; set; }
          public string UserName { get; set; }
          public string Password { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public string Email { get; set; }
      }
  }
  </code></pre>
  
  <p><strong>IUserRepository.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace WebAPIv2.Models
  {
      interface IUserRepository
      {
          List&lt;TableUser&gt; GetAll();
          TableUser Get(int id);
          TableUser Add(TableUser user);
          void Remove(int id);
          bool Update(TableUser user);
      }
  }
  </code></pre>
  
  <p><strong>UserRepository.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  
  namespace WebAPIv2.Models
  {
      public class UserRepository : IUserRepository
      {
          MastarsFriendsMVCDatabaseEntities userEntities;
  
          public UserRepository()
          {
              userEntities = new MastarsFriendsMVCDatabaseEntities();
          }
  
          public List&lt;TableUser&gt; GetAll()
          {
              //throw new NotImplementedException();
  
              return userEntities.TableUsers.ToList();
          }
  
          public TableUser Get(int id)
          {
              //throw new NotImplementedException();
  
              var users = userEntities.TableUsers.Where(x =&gt; x.UserId == id);
              if (users.Count() &gt; 0)
              {
                  return users.Single();
              }
              else
              {
                  return null;
              }
          }
  
          public TableUser Add(TableUser user)
          {
              //throw new NotImplementedException();
  
              if (user == null)
              {
                  throw new ArgumentNullException("item");
              }
              userEntities.TableUsers.Add(user);
              userEntities.SaveChanges();
              return user;
          }
  
          public void Remove(int id)
          {
              //throw new NotImplementedException();
  
              TableUser user = Get(id);
              if (user != null)
              {
                  userEntities.TableUsers.Remove(user);
                  userEntities.SaveChanges();
              }
          }
  
          public bool Update(TableUser user)
          {
              //throw new NotImplementedException();
  
              if (user == null)
              {
                  throw new ArgumentNullException("student");
              }
  
              TableUser userInDB = Get(user.UserId);
  
              if (userInDB == null)
              {
                  return false;
              }
  
              userEntities.TableUsers.Remove(userInDB);
              userEntities.SaveChanges();
  
              userEntities.TableUsers.Add(user);
              userEntities.SaveChanges();
  
              return true;
          }
      }
  }
  </code></pre>
  
  <p><strong>WebApiConfig.cs:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net.Http.Headers;
  using System.Web.Http;
  
  namespace WebAPIv2
  {
      public static class WebApiConfig
      {
          public static void Register(HttpConfiguration config)
          {
              // Web API configuration and services
  
              // Web API routes
              config.MapHttpAttributeRoutes();
              //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
              config.Routes.MapHttpRoute(
                  name: "DefaultApi",
                  routeTemplate: "api/{controller}/{id}",
                  defaults: new { id = RouteParameter.Optional }
              );
          }
      }
  }
  </code></pre>
  
  <p><strong>index.html:</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;TODO supply a title&lt;/title&gt;
          &lt;meta charset="UTF-8"&gt;
          &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  
          &lt;!--&lt;script src="http://code.jquery.com/jquery-1.9.1.min.js"&gt;&lt;/script&gt;--&gt;
          &lt;script src="http://code.jquery.com/jquery-2.1.0.min.js"&gt;&lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;script&gt;
              $(document).ready(function() {
  //                jQuery.support.cors = true;
  //                $.ajax({
  //                    url: "http://localhost:1176/api/user/1",
  //                    headers: {"Accept": "application/json"},
  //                    type: "GET",
  //                    success: function(data) {
  //                        alert(JSON.stringify(data));
  //                    },
  //                    error: function() {
  //                        alert("Error");
  //                    }
  //                });
  //            });
  
                  var user = {
                      UserName: "Disha",
                      Password: "disha123",
                      FirstName: "Disha",
                      LastName: "Vora",
                      Email: "disha@pixielit.com"
                  };
  
                  $.ajax({
                      url: 'http://localhost:1176/api/user/',
                      type: 'POST',
                      data: JSON.stringify(user),
                      crossDomain: true,
                      headers: {"Accept":"application/json" , "Content-Type":"application/json"},
                      success: function(data) {
                          alert('User added Successfully');
                      },
                      error: function() {
                          alert('User not Added');
                      }
                  });
              });
          &lt;/script&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>Web.config:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;!--
    For more information on how to configure your ASP.NET application, please visit
    http://go.microsoft.com/fwlink/?LinkId=301879
    --&gt;
  &lt;configuration&gt;
    &lt;configSections&gt;
      &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt;
      &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;
    &lt;/configSections&gt;
    &lt;appSettings&gt;&lt;/appSettings&gt;
    &lt;system.web&gt;
      &lt;compilation debug="true" targetFramework="4.5"&gt;
        &lt;assemblies&gt;
          &lt;add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt;
        &lt;/assemblies&gt;
      &lt;/compilation&gt;
      &lt;httpRuntime targetFramework="4.5" /&gt;
    &lt;/system.web&gt;
    &lt;system.webServer&gt;
      &lt;validation validateIntegratedModeConfiguration="false" /&gt;
      &lt;modules runAllManagedModulesForAllRequests="true"&gt;
        &lt;remove name="WebDAVModule" /&gt;
      &lt;/modules&gt;
      &lt;httpProtocol&gt;
        &lt;customHeaders&gt;
          &lt;add name="Access-Control-Allow-Origin" value="*" /&gt;
          &lt;add name="Access-Control-Request-Headers:" value="*" /&gt;
          &lt;add name="Access-Control-Request-Method:" value="*" /&gt;
          &lt;add name="Access-Control-Allow-Methods" value="*" /&gt;
          &lt;!--&lt;add name="Allow" value="*"/&gt;--&gt;
        &lt;/customHeaders&gt;
      &lt;/httpProtocol&gt;
      &lt;handlers&gt;
        &lt;remove name="WebDAV" /&gt;
        &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt;
        &lt;remove name="OPTIONSVerbHandler" /&gt;
        &lt;remove name="TRACEVerbHandler" /&gt;
        &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt;
      &lt;/handlers&gt;
      &lt;directoryBrowse enabled="true" /&gt;
    &lt;/system.webServer&gt;
    &lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt;
        &lt;parameters&gt;
          &lt;parameter value="v11.0" /&gt;
        &lt;/parameters&gt;
      &lt;/defaultConnectionFactory&gt;
    &lt;/entityFramework&gt;
    &lt;connectionStrings&gt;
      &lt;add name="MastarsFriendsMVCDatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=WIN-WWU3DMLR6PX\PIXIELIT;initial catalog=MastarsFriendsMVCDatabase;persist security info=True;user id=sa;password=sa_12345;MultipleActiveResultSets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient" /&gt;
    &lt;/connectionStrings&gt;
  &lt;/configuration&gt;
  </code></pre>