2016-01-28 88 views
5

我有一個Web Api控制器。它表現得很奇怪。當我使用PostMan時,我可以訪問Web Api上的POST方法,但是當我使用.net中的HttpWebRequest時,它返回(405)方法不允許。 我在這裏把網頁API代碼:ASP.NET WebApi:(405)方法不允許

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 

我會很感激任何解決問題的建議。

回答

1

我找到了解決方案啓用一個Cors。

我檢查由Fiddler.When請求我發送POST請求API自動重定向到相同的地址與這個新的參數AspxAutoDetectCookieSupport=1

How to remove AspxAutoDetectCookieSupport=1

最後我在web.config中改變了cookieless="AutoDetect"cookieless="UseCookies"並解決了問題。

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

您很可能不會發送正確的x-www-form-urlencoded請求。您可能無法正確編碼從postParameters傳入的任何數據。請參閱Post form data using HttpWebRequest

由於您未根據x-www-form-urlencoded生成有效的OrderResult對象,因此路由選擇器不會選擇您的Buy操作。這就是爲什麼你得到POST是不允許的。

如果您更改了OrderResult value = null,您可能會收到控制器,因爲它現在是一個可選參數。然而,這是不是你想要的,除非你將有一個奇怪的控制其行爲類似:

Buy(OrderResult value = null) 
{ 
    if(value== null) 
     value = MyCustomDeserializeFromRequestBody(RequestContext) 

    ... 
} 

最終你剛纔真的不應該有現代發展https://stackoverflow.com/a/31147762/37055https://github.com/hhariri/EasyHttp更好的構造使用這個類關閉我的頭頂