当我在ASP.NET WebAPI CORS中发送POST数据时,HTTP CODE 405(不允许使用方法) [英] HTTP CODE 405 (Method Not Allowed), When I sent POST data in ASP.NET WebAPI CORS

查看:322
本文介绍了当我在ASP.NET WebAPI CORS中发送POST数据时,HTTP CODE 405(不允许使用方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Web.config

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>

控制器

  [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

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

浏览器错误:

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

我可以通过 GET 方法获取API。我很奇怪,我可以通过 POST 方法从API获得响应,而无需任何参数。否则,我只会收到http错误405。

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.

此外,我也会从DELETE和PUT方法中收到HTTP错误405。只有GET和Option返回httpcode200。

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

推荐答案

检查此内容:发布Web API 2应用程序后,对HTTP 405错误进行故障排除

MVC -Web API:不允许使用405方法

将数据传递到您的方式存在问题方法,当您尝试传递多个参数时,应尝试如下操作

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

您的ajax调用必须类似于

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

您的网络api方法将像这样

and you web api method will be like this

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

也请在此处查看帖子: http://weblog.west-wind.com / posts / 2012 / May / 08 /将多个POST参数传递到Web API控制器方法

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

这篇关于当我在ASP.NET WebAPI CORS中发送POST数据时,HTTP CODE 405(不允许使用方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆