我需要在C#中使用HttpWebRequest提供帮助。下面的代码行适用于本地IIS,但是当我上传到远程服务器时,它开始给我“远程服务器返回错误:(500)内部服务器错误。”。我用GET和POST方法尝试了很多变化,但无法弄清楚问题是什么。请查看下面的代码,让我知道这有什么问题。
try
{
string postData = "applicaitonid=abc&deviceid=xyz";
string uri = System.Configuration.ConfigurationManager.AppSettings.Get("baseUrl") + System.Configuration.ConfigurationManager.AppSettings.Get("ABApiPath") + "ConfirmAppBinding/?" + postData;
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST"; // Set type Post
//request.Method = "GET";
request.UserAgent = Request.UserAgent.ToString();
request.ContentType = @"application/json";
request.MediaType = "application/json";
request.Accept = "application/json";
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
//byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(postData);
request.Timeout = 500000; //Increase timeout for testing
Stream reqstr = request.GetRequestStream();
//reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
// Read Response
var httpResponse = request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
JsonMessage.message = streamReader.ReadToEnd();
streamReader.Close();
}
}
catch (WebException e)
{
JsonMessage.message = e.Message;
return Json(JsonMessage, JsonRequestBehavior.AllowGet);
}
正如我告诉过你的,我使用了默认的GET方法,但它没有解决问题。
答案 0 :(得分:9)
将此代码用于catch
catch (WebException e)
{
string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
return pageContent;
}
它会显示您面临的确切错误。
答案 1 :(得分:1)
我会在黑暗中刺伤
你的查询字符串中是否存在拼写错误?当引用代码中的密钥时,它会返回nullvalue异常?
{ String postData = "applicaitonid=abc&deviceid=xyz";
}
应该是
{ String postData = "applicationid=abc&deviceid=xyz"; }
答案 2 :(得分:1)
您可以使用try and catch块查找根本原因。
catch (WebException ex)
{
string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}