Asp.net
ASP.NET WebApi:(405)方法不允許
我有一個 Web Api 控制器。它的行為非常奇怪。當我使用 PostMan 時,我可以訪問 Web Api 上的 POST 方法,但是當我從 .net 使用 HttpWebRequest 時,它返回 (405) Method Not Allowed。我把 Web Api 程式碼放在這裡:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace MyProject.Controllers { public class TestController : ApiController { [HttpPost] public int buy(OrderResult value) { try { if (value.InvoiceDate != null && value.Result == 1) { return 0; } } catch{} return -1; } } public class OrderResult { public int Result { get; set; } public long InvoiceNumber { get; set; } public string InvoiceDate { get; set; } public long TimeStamp { get; set; } } }這是我的 WebApiConfig.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace MyProject { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional } ); } } }這就是我從另一個 .NET 項目發送 POST 請求的方式:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace MyProject.Controllers { public static class WebReq { public static string PostRequest(string Url, string postParameters) { try { HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(Url); myReq.Method = "POST"; myReq.Timeout = 30000; myReq.Proxy = null; byte[] postData = Encoding.UTF8.GetBytes(postParameters); myReq.ContentLength = postData.Length; myReq.ContentType = "application/x-www-form-urlencoded"; using (Stream requestWrite = myReq.GetRequestStream()) { requestWrite.Write(postData, 0, postData.Length); requestWrite.Close(); using (HttpWebResponse webResponse = (HttpWebResponse)myReq.GetResponse()) { if (webResponse.StatusCode == HttpStatusCode.OK) { using (Stream str = webResponse.GetResponseStream()) { using (StreamReader sr = new StreamReader(str)) { return sr.ReadToEnd(); } } } return null; } } } catch (Exception e) { var message = e.Message; return null; } } } }我已經在我的 web.config 中添加了以下程式碼:
<modules runAllManagedModulesForAllRequests="true"> <remove name="WebDAVModule" /> </modules>這很奇怪,因為我可以從 PostMan 成功發送 POST 請求。PostMan 將此程式碼發送到 API。
POST /api/Test/buy HTTP/1.1 Host: domain.com Cache-Control: no-cache Postman-Token: 9220a4e6-e707-5c5f-ea61-55171a5dd95f Content-Type: application/x-www-form-urlencoded InvoiceDate=28012016&Result=1我將不勝感激任何解決問題的建議。
我找到了解決方案。
我檢查了 Fiddler 的請求。當我向 API 發送 POST 請求時,它會使用這個新參數自動重定向到相同的地址
AspxAutoDetectCookieSupport=1如何刪除 AspxAutoDetectCookieSupport=1
最後我將
cookieless="AutoDetect"web.config中的更改為cookieless="UseCookies"並解決了問題。
我知道這是一篇舊文章,但也許這可能對其他人有所幫助。我剛剛遇到了類似的問題,當我顯然在郵遞員中發帖時收到 405 錯誤“不允許”。原來,我使用 http 而不是 https 送出到 URL。更改為 https 修復它。