c#WCF JSON POST - (400)错误请求

时间:2015-08-26 22:30:50

标签: c# json wcf

我尝试了一切!

我总是得到一个"(400)错误请求"我尝试从客户端调用WCF服务时出错。

我想通过JSON发送给服务器a'用户'类

我的代码:

计算值

 [OperationContract]
 [WebInvoke(Method="POST",
        RequestFormat=WebMessageFormat.Json,
        ResponseFormat=WebMessageFormat.Json,
        UriTemplate = "/UplaodData")]
void PostUser(Users user);

界面ICalc

 public void PostUser(Users user)
 {
     int userId = user.id;
     .....
 }

的Web.config

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="mydbConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="WebDAVModule"/>
    </modules>
    <handlers>
      <remove name="WebDAV"/>
    </handlers>
  </system.webServer>
  <system.serviceModel>
    <services>
      <service name="Calc">
        <endpoint address="" behaviorConfiguration="DualHttp"
                  binding="webHttpBinding" contract="ICalc"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <!-- we added this -->
        <behavior name="DualHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
</configuration>

客户端

private void btnAdd_Click(object sender, EventArgs e)
{
    if(ValidateChildren(ValidationConstraints.Enabled))
    {
        var user = new Users();
        user.id = 1;
        user.birthday = new DateTime(2009,1,1);
        WebClient Proxy = new WebClient();
        Proxy.Headers["Content-type"] = "application/json";
        MemoryStream ms = new MemoryStream();
        var serializerToUpload = new DataContractJsonSerializer(typeof(Users));
        serializerToUpload.WriteObject(ms, user);
        proxy.UploadData(basicURL + "UplaodData", "POST", ms.ToArray());
    }
}

修改

private string basicURL = string.Format("http://localhost:20524/finalProjectServer/Service.svc/");
private WebClient proxy = new WebClient();

0 个答案:

没有答案