Ajax post HTML 405,asp.net web api - Ajax Post: 405 Method Not Allowed - Stack Overflow

Within my API Controller called Payment, I have the following method:

[HttpPost]

public HttpResponseMessage Charge(Payment payment)

{

var processedPayment = _paymentProcessor.Charge(payment);

var response = Request.CreateResponse(processedPayment.Status != "PAID" ? HttpStatusCode.ExpectationFailed : HttpStatusCode.OK, processedPayment);

return response;

}

In my HTML page I have:

$.ajax({

type: "POST",

contentType: "application/json; charset=utf-8",

url: "http://localhost:65396/api/payment/charge",

data: $('#addPayment').serialize(),

dataType: "json",

success: function (data) {

alert(data);

}

});

Whenever I fire the POST, I get

"NetworkError: 405 Method Not Allowed - http://localhost:65396/api/payment/charge"

What am I missing?

Thank you.

UPDATE

Here's the routing information (default)

routes.MapHttpRoute(

name: "DefaultApi",

routeTemplate: "api/{controller}/{id}",

defaults: new { id = RouteParameter.Optional }

);

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HTTP 405错误通常发生在使用Ajax调用Web API时,这是因为Web API默认情况下只支持GET和POST请求,而不支持PUT、DELETE、OPTIONS等请求方法。解决这个问题的方法是在Web API端添加一个处理OPTIONS请求的方法。 在Web API中,可以使用Web API的CORS功能来解决这个问题。CORS(跨域资源共享)是一种Web标准,允许在不同域名下的浏览器访问服务器资源。 为了启用CORS,需要在Web API项目中安装Microsoft.AspNet.WebApi.Cors NuGet包。然后,在WebApiConfig类中启用CORS: ``` using System.Web.Http; using System.Web.Http.Cors; public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 启用CORS var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); // ...其他配置 } } ``` 这里的“*”表示允许任何域名、任何方法、任何标头访问Web API。你也可以指定具体的域名、方法和标头。 在客户端使用Ajax时,需要设置withCredentials为true,这样才能在跨域请求时发送Cookies和认证信息。例如: ``` $.ajax({ type: "POST", url: "http://example.com/api/resource", data: JSON.stringify({data: "hello"}), contentType: "application/json", xhrFields: { withCredentials: true }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.log(xhr.responseText); } }); ``` 在这个例子中,我们向http://example.com/api/resource发送一个带有数据的POST请求,并设置withCredentials为true,以便发送Cookies和认证信息。如果请求成功,我们将收到响应数据,并将其打印到控制台中。如果请求失败,我们将打印xhr.responseText,这包含了服务器返回的错误信息。 希望这个解决方案可以帮助你解决问题!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值