2014-09-22 60 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

相关问题