我无法使用POST来使用我的ASP.NET Web API 2服务器

时间:2014-09-22 18:03:22

标签: asp.net-web-api2

我正在使用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,我会收回数据。

但我尝试向http://localhost:13770/license/exchange发帖,我得到:

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: 

我打电话使用:

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

我做错了什么?

1 个答案:

答案 0 :(得分:-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查看文档。