2014-09-22 63 views
0

我使用的Web API 2.我已經在我的控制器以下(及以上):我不能得到一個POST與我的ASP.NET Web API工作2服務器

[Route("about")] 
    public string GetAbout() 
    { 
     IPrincipal principal = RequestContext.Principal; 
     IPrincipal user = User; 
     return string.Format("principal: {0}, user: {1}", principal == null || principal.Identity == null ? null : principal.Identity.Name, 
      user == null ? null : user.Identity.Name); 
    } 
    [Route("license/exchange")] 
    //public string PostUser([FromBody]string value) 
    public XmlDocument PostLicenseExchange(XmlDocument xml) 
    { 
     Trap.trap(); 
     int x = 3; 
     return xml; 
    } 

在我的瀏覽器,如果我輸入URI http://localhost:13770/about,我就會收到數據。

但我我嘗試了POST到http://localhost:13770/license/exchange,我得到:

Start() { 
       // start the request 
       Uri httpSite = new Uri(URI_LICENSE_SERVER); 
       WebRequest wreq = WebRequest.Create(httpSite); 
       wreq.Method = "POST"; 
       wreq.ContentType = "text/xml"; 

       RequestState requestState = new RequestState(asyncCallback, xmlDoc.ToString(SaveOptions.DisableFormatting), msgGuid, wreq); 
       wreq.BeginGetRequestStream(GetRequestStreamCallback, requestState); 
} 
     private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) 
     { 
      RequestState requestState = (RequestState)asynchronousResult.AsyncState; 
       using (Stream postStream = requestState.Request.EndGetRequestStream(asynchronousResult)) 
       { 
        byte[] byteArray = Encoding.UTF8.GetBytes(requestState.XmlRequest); 
        postStream.Write(byteArray, 0, byteArray.Length); 
        postStream.Close(); 
       } 
       requestState.Request.BeginGetResponse(GetResponseCallback, requestState); 

     } 

     private static void GetResponseCallback(IAsyncResult asynchronousResult) 
     { 
      RequestState requestState = (RequestState)asynchronousResult.AsyncState; 
// exception on this call 
       using (HttpWebResponse response = (HttpWebResponse) requestState.Request.EndGetResponse(asynchronousResult)) 

我在做什麼錯:

System.Net.WebException occurred 
    Message=The remote server returned an error: (401) Unauthorized. 
    Source=System 
    StackTrace: 
     at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 
     at EnforcedVacationCommon.LicenseServer.ServerComm.GetResponseCallback(IAsyncResult asynchronousResult) in c:\src\EnforcedVacation\EnforcedVacationCommon\LicenseServer\ServerComm.cs:line 137 
    InnerException: 

我使用打電話?

回答

-2

您需要指定這是一個帶有操作結果屬性的Http Post方法。

[HttpPost] 
    [Route("license/exchange")] 
    //public string PostUser([FromBody]string value) 
    public XmlDocument PostLicenseExchange(XmlDocument xml) 
    { 
     Trap.trap(); 
     int x = 3; 
     return xml; 
    } 

您可以通過clicking here查看文檔。

+1

我不認爲這是必要的,因爲文檔說 - 「默認情況下,Web API尋找與控制器方法名稱的開頭不區分大小寫的匹配。」所以PostLicenseExchage應該匹配HttpPost。 – Guanxi 2014-09-23 17:27:32

+0

不幸的是,補充說沒有幫助。 – 2014-09-23 17:35:42

相關問題