[英]Getting Error Code 400 Bad Request for Rest WCF Client
我正在使用通過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>
造成這種錯誤的原因很多。 嘗試如下更改元數據-
[WebInvoke(UriTemplate = "/Category/Add", Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
bool AddCategory(string category);
我看過一些文章,指出您需要使用webHttpBinding才能起作用。 可能有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.