在WCF服务中接收POST数据

时间:2012-12-11 21:22:27

标签: wcf post

我阅读了很多教程,但是我的项目无法运行。我提供了很少的GET服务来发送数据并且它们工作得很好,但是我在接收数据时遇到了问题。如果有人能告诉我失败的地方,而不是发布一些链接,我真的很感激。 :) 当我尝试在浏览器中调用该服务时,我收到错误:不允许使用方法。但我认为这只是第一个错误。

这是我的代码。 首先是Android中我称之为服务的代码:

public class MainActivity extends Activity {

String SERVICE_URI = "http://10.0.2.2:51602/RestServiceImpl.svc";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    HttpPost request = new HttpPost(SERVICE_URI + "/registerUser");
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");

    try {
        JSONStringer user = new JSONStringer()
                .object()
                .key("userInfo")
                .object()
                    .key("Email").value("mail")
                    .key("Password").value("pass")
                    .key("Cauntry").value("country")
                    .key("UserName").value("username")
                .endObject()
        .endObject();

        StringEntity entity = new StringEntity(user.toString());
        request.setEntity(entity);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);


        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

IRestServiceImpl.cs:

[ServiceContract]
public interface IRestServiceImpl
{
    [OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "registerUser",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    void receiveData(String data);
}

RestServiceImpl.cs:

public class RestServiceImpl : IRestServiceImpl
{
    public void receiveData(String data)
    {
        //some code
    }
}

的Web.config:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">

        <endpoint address ="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web">

        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

1 个答案:

答案 0 :(得分:1)

您的问题是您正在将JSON 对象传递给操作,但该操作需要JSON 字符串。如果我正确理解了Java代码,那就是你要发送的内容:

{
    "userInfo" : {
        "Email" : "mail",
        "Password" : "pass",
        "Cauntry" : "country",
        "UserName" : "username"
    }
}

这不是JSON字符串。

你可以做几件事。第一种方法是修改操作不要接受字符串,而是采用与该对象等效的数据合约。

代码看起来像下面的代码。请注意,您还应将正文格式更改为Bare(而不是Wrapped)。

public class RequestData
{
    public UserInfo userInfo { get; set; }
}

public class UserInfo
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string Cauntry { get; set; } // typo to match the OP
    public string UserName { get; set; }
}

[ServiceContract]
public interface IRestServiceImpl
{
    [OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "registerUser",
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    void receiveData(RequestData data);
}

另一种选择,如果数据的“模式”每次都发生变化,那么将输入作为 Stream (而不是String)。这样你基本上可以接受任何输入。您可能还需要内容类型映射器。您可以在http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx找到有关此方案的更多信息。