当我使用POSTMAN或Fiddler测试它时,我创建了一个C#WCF项目。我收到一条错误消息:“400 Bad Request”。我也创建了一个C#windows项目进行测试,结果也是如此。这是我的WCF项目。
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "api/createpr.json")]
PRApplication AddPR(RequestData rData);
}
我在测试时使用此代码。
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/WEB_Service_B1/Service1.svc/api/createpr.json");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"Test\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
我的Web.config中是否还有问题?
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.webServer>
<directoryBrowse enabled="true"/>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WS_B1.Service1Behavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WS_B1.Service1" behaviorConfiguration="WS_B1.Service1Behavior">
<endpoint address="" binding="webHttpBinding" contract="WS_B1.IService1" behaviorConfiguration="web">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
</configuration>
答案 0 :(得分:2)
BodyStyle = WebMessageBodyStyle.Wrapped
这意味着请求需要是一个完整的json对象。尝试使用以下请求正文:
string json = "{\"rData\": {\"PropertyName\": \"Test\"}}";
其中PropertyName
是RequestData
字符串类型的公共属性。