Asp.net-Web-Api
Ajax 文章:不允許使用 405 方法
在我的稱為 Payment 的 API 控制器中,我有以下方法:
[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; }在我的 HTML 頁面中,我有:
$.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); } });每當我啟動 POST 時,我都會得到
"NetworkError: 405 Method Not Allowed - http://localhost:65396/api/payment/charge"我錯過了什麼?
謝謝你。
更新
這是路由資訊(預設)
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 } );
原來我需要實現 CORS 支持。http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx
很可能沒有為要呼叫的操作配置您的路由。因此,請求最終無處可去,並且 ASP.NET Web API 發送了一條空白消息“方法不允許”。
你能用你的路由更新問題嗎?
更新
和我想像的一樣!您正在發送到,
http://localhost:65396/api/payment/charge而您需要發送到http://localhost:65396/api/payment- 假設您的控制器被呼叫PaymentController。請注意,路線沒有
action.