3

Web.config

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

Controller

  [EnableCors(origins: "http://domain/api/Clients", headers: "*", methods: "*")]
public class ClientsController : ApiController
{
    private ParaNewnergyEntities db = new ParaNewnergyEntities();

    // GET: api/Clients
    public IEnumerable<Client> GetClient()
    {
        return db.Client.ToList();
    }
    [HttpPost]
    public IHttpActionResult PostClient(String Username, String Password)
    {
        Client c = new Client
        {
            Username = Username,
            Password = Password
        };

        db.Client.Add(c);
        db.SaveChanges();
        return Ok(c);
    }

WebApiConfig.cs

     public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.EnableCors();

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

    }

Ajax

   var sendData={
            Username:"gx",
            Password:"gx"
        };
        $.ajax({
            url: "http://domain/api/Clients",
            type: "POST",
            data: sendData,
            success: function (d) {
                $("#msg").html(d);
                console.log(d);
            }
        });

Browser Error:

  POST http://domain/api/Clients 405 (Method Not Allowed)

I can get API by GET method. It is very weirdo that I can get response from API by POST method without Any Parameter. Otherwise, I just got http error 405.

In addition, I get http error 405 from DELETE and PUT method, too. Only GET and Option return httpcode 200.

Gaoxin Huang
  • 178
  • 1
  • 2
  • 9
  • I have used one parameter now. The http code is 415 now – Gaoxin Huang May 30 '16 at 09:56
  • I have already solved the problem. My problem is: 1. In APIController, If I want to pass multiple parameters, I should put them into the one parameter as Pranay said. It made me got 405. 2. I have some issues in my model attributes. That is why my code got 500. – Gaoxin Huang May 31 '16 at 23:46

1 Answers1

2

Check this : Troubleshooting HTTP 405 Errors after Publishing Web API 2 Applications

MVC-Web API: 405 method not allowed


There is problem with the way you are passing data to your method, as you are trying to pass multiple parameter you should try as below

you ajax call need to be like

var client = {
    Username:"gx",
    Password:"gx"
}
$.ajax(
{
    url: "http://domain/api/Clients",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(client),
    success: function (result) {
        alert(result);
    }
});

and you web api method will be like this

[HttpPost]
    public IHttpActionResult PostClient(Client client)
    {
        db.Client.Add(client);
        db.SaveChanges();
        return Ok(client);
    }

Also check post here : http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • Hi, Thank you for your answer. I have tried your answer below. However, I got error 500: – Gaoxin Huang May 30 '16 at 06:07
  • @GaoxinHuang - check this : http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications – Pranay Rana May 30 '16 at 07:06
  • @GaoxinHuang - check this response also http://stackoverflow.com/questions/23293782/mvc-web-api-405-method-not-allowed – Pranay Rana May 30 '16 at 07:14
  • I have already read and tried the above two links. It does not work. Sorry. my httpcode is 415 After using one parameter – Gaoxin Huang May 30 '16 at 09:55