我正在开发一个通过get和post方法向wcf rest服务发送请求的应用程序。就我而言,GET
方法运行正常。但在POST
方法中,我总是收到错误代码400 Bad Request
。
我的客户端代码: -
string strInput = HttpUtility.UrlEncode("ab");
byte[] data = GetBytes(strInput);
//data = System.Text.ASCIIEncoding.ASCII.GetBytes(strInput);
data = UTF8Encoding.UTF8.GetBytes(strInput);
Stream objStream;
WebRequest request = WebRequest.Create("http://localhost:9010/SampleServices/Service/Test/Category/Add");
request.Method = "POST";
request.ContentLength = data.Length;
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "text/xml";
//request.ContentType = "application/x-www-urlencoded";
objStream = request.GetRequestStream();
objStream.Write(data, 0, data.Length);
objStream.Close();
WebResponse ws = request.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader responseStream = new StreamReader(ws.GetResponseStream());
string response = responseStream.ReadToEnd();
responseStream.Close();
MessageBox.Show(response);
服务器端代码: -
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(UriTemplate = "/Category/{categoryID}", Method = "GET")]
Category GetCategory(string CategoryID);
[OperationContract]
[WebInvoke(UriTemplate = "/Category/Add", Method = "POST")]
bool AddCategory(string category);
}
public class Service : IService
{
public Category GetCategory(string categoryID)
{
NorthwindDataContext context = new NorthwindDataContext();
var category = context.Categories.SingleOrDefault(e => e.CategoryID == Convert.ToInt32(categoryID));
context.Dispose();
return category;
}
public bool AddCategory(string category)
{
//NorthwindDataContext context = new NorthwindDataContext();
//context.Categories.InsertOnSubmit(category);
//context.SubmitChanges();
//context.Dispose();
return true;
}
}
我尝试了不同的内容类型选项,并尝试使用Url编码参数字符串但仍然遇到同样的问题。这可能是因为HttpGet
工作正常的原因。为什么HttpPost
存在问题?
WCF配置: -
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="SampleServices.Service" behaviorConfiguration="MYServiceBehavior">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint address="net.tcp://localhost:12000/SampleServices/Service" binding="netTcpBinding" bindingConfiguration="TCPBindingDetails" contract="SampleServices.IService" behaviorConfiguration="TCPBehavior">
</endpoint>
<endpoint name="webHttpBinding" address="REST" binding="webHttpBinding" behaviorConfiguration="RESTBehavior" contract="SampleServices.IService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:9002/SampleServices/Service/" />
</baseAddresses>
<timeouts closeTimeout="01:20:10" openTimeout="01:20:00" />
</host>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="TCPBindingDetails" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="5000000" maxBufferSize="5000000" maxConnections="10" maxReceivedMessageSize="5000000">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:30:00" enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="None" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<clear />
<behavior name="TCPBehavior">
<dataContractSerializer maxItemsInObjectGraph="6553600" />
</behavior>
<behavior name="RESTBehavior">
<dataContractSerializer maxItemsInObjectGraph="6553600" />
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MYServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
</configuration>
答案 0 :(得分:0)
导致此类错误的原因很多。尝试更改下面的元数据 -
[WebInvoke(UriTemplate = "/Category/Add", Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
bool AddCategory(string category);
答案 1 :(得分:0)
我看过一些文章表明你需要使用webHttpBinding来实现这一点。这可能会有所帮助