我正在使用以下代码将XML文件发送到服务器,如果我上传adduser.xml
(这是用于添加用户),我正在获得成功响应,但是对于deleteuser.xml
(这是delete的用户用户)我得到
远程服务器返回一个错误:(400)
错误的请求。在system.net.httpwebrequest.getResponse()
在deleteuser.page_load(对象发送者,EventArgs e)
我尝试过方法类型PUT
,GET
,POST
和DELETE
,但有相同的错误。
你能帮我我做错了什么吗?
public partial class DeleteUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string fileName = Server.MapPath("~/deleteuser.xml");
string uri = "http://test.com/AuctionUsers/delete";
req = WebRequest.Create(uri);
req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST";
req.ContentType = "application/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse(); //I am getting error over here
StreamReader sr = new StreamReader(rsp.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
Response.Write(result);
}
catch (WebException webEx)
{
Response.Write(webEx.Message.ToString());
Response.Write(webEx.StackTrace.ToString());
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
Response.Write(ex.StackTrace.ToString());
}
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}
private string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
}
预先感谢您。
可能有几个不同的原因,其中一个是该方法本身的错误。如果您有访问权限,我会首先建议在服务器端上进行跟踪;它可以帮助您查明错误。引用链接,看起来应该像这样:
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:logTraces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
然后可以从.NET跟踪查看器中查看其生成的文件。
编辑:这里有类似的帖子,可以有一些帮助:
为什么远程服务器返回错误:(400)不良请求。?