我在 C# 中创建了一个安静的 Web 服务。调用 POST 方法时出现 400 错误请求错误。我正在 fiddler 中检查我的请求,POST 请求非常好。我不明白我的程序有什么问题。
以下是一些代码片段。如果你们中的任何人需要任何其他代码来查看,请询问。
界面
[ServiceContract]
public interface IRead
{
[OperationContract]
[WebInvoke(UriTemplate = "GetCard", Method = "POST")]
someObject GetCard(Session session);
}
NFCSession 是一个具有名称 session 的 int 变量的对象。
客户端生成 POST 请求
public void GetCard()
{
string strGetCard = "http://localhost:8384/Reader/GetCard";
byte[] dataByte = GenerateNFCSession(63315152);
HttpWebRequest POSTRequest = (HttpWebRequest)WebRequest.Create(strGetCard);
POSTRequest.Method = "POST";
POSTRequest.ContentType = "application/xml;charset=UTF-8";
POSTRequest.ContentLength = dataByte.Length;
Stream POSTstream = POSTRequest.GetRequestStream();
POSTstream.Write(dataByte, 0, dataByte.Length);
HttpWebResponse POSTResponse = (HttpWebResponse)POSTRequest.GetResponse();
StreamReader reader =
new StreamReader(POSTResponse.GetResponseStream(), Encoding.UTF8);
Console.WriteLine("Response");
Console.WriteLine(reader.ReadToEnd().ToString());
}
XML 生成器
private static byte[] GenerateXML(int sessionID)
{
MemoryStream mStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(mStream, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Session");
xmlWriter.WriteStartElement("session");
xmlWriter.WriteString(sessionID.ToString());
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
Console.WriteLine(mStream.ToArray().ToString());
return mStream.ToArray();
}
网络配置
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
System.Web,Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" faultExceptionEnabled="true"
automaticFormatSelectionEnabled="true"></standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
来自 Fiddler 的 POST 请求 XML
<?xml version="1.0" encoding="utf-8"?>
<Session>
<session>63315152</session>
</Session>
我收到这个错误
The server encountered an error processing the request.
注意:当我提供 XmlSerializer 格式属性时,它工作正常。但我希望我的服务以后也能处理 JSON 请求。而且从我的角度来看,没有必要明确提供格式属性。我真的不明白这段代码有什么问题。
伙计们请帮忙!!!