簡體   English   中英

.NET Web服務接收HTTP POST請求(500)內部服務器錯誤

[英].NET Web Service receive HTTP POST request (500) Internal Server Error

我目前正在編寫一個C#Web服務,它有幾種方法,其中一種方法必須接收HTTP POST請求。 我做的第一件事是改變web服務項目中的web.config文件,如下所示。

<webServices>
  <protocols>
    <add name="HttpSoap"/>
    <add name="HttpPost"/>
    <add name="HttpPostLocalhost"/>
    <add name="Documentation"/>
  </protocols>
</webServices>

我可以在本地運行Web服務,當我在瀏覽器中單擊該方法時,我可以看到它處理HTTP POST請求並接受args = string,因為我的Web方法簽名接受一個名為args的字符串參數。 然后我通過測試ASP.NET應用程序使用下面的代碼測試它來觸發HTTP POST請求。

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ConfigurationManager.AppSettings["PaymentHubURL"].ToString());

request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";

StringBuilder sb = new StringBuilder();
sb.Append("message_type=");
sb.Append(HttpUtility.UrlEncode("Txn_Response"));

byte[] bytes = UTF8Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = bytes.Length;
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(bytes, 0, bytes.Length);
}

string test;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
     StreamReader reader = new StreamReader(response.GetResponseStream());

     test = reader.ReadToEnd();
}

但是當我運行這個時,我得到“遠程服務器返回錯誤:(500)內部服務器錯誤”。 如果我刪除參數,通過刪除stringbuilder和字節代碼,以及在Web服務中沒有參數,它的工作原理。 所以這顯然是參數的問題。 我實際上想要發送更多數據,並在Web服務中使用string []參數,但這也失敗了。

誰能幫忙?

我建議你重新考慮你的方法。 微軟已經編寫了非常棒的用於使用Web服務的庫,但有兩種方法可以實現 - “添加Web引用”和“添加服務引用”。

在您的情況下,似乎您有一個“asmx Web服務”,所以我建議您在visual studio中為您的項目添加“Web引用”。 這假設您正在使用visual studio。

添加此Web引用后,您可以通過“new”創建客戶端。 您可以在此客戶端上執行任何Web方法。 這是使用Web服務的最簡單方法。 您不必處理任何http並發症。

希望這可以幫助。

我猜你是在錯誤地構建HttpPost請求。

嘗試使用以下鏈接中顯示的代碼來創建您的請求:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

或者可能響應不包含unicode char值

嘗試復制並粘貼此代碼以獲取響應

 System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    StreamReader objSR;

webResponse = (HttpWebResponse)response.GetResponse();
StreamReader reader = webResponse.GetResponseStream();
objSR = new StreamReader(objStream, encode, true);
sResponse = objSR.ReadToEnd();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM