【问题标题】:Receiving POST data in WCF Service在 WCF 服务中接收 POST 数据
【发布时间】:2014-07-06 19:13:58
【问题描述】:

我阅读了很多教程,但我无法在我的项目中运行它。我做了一些发送数据的 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>

【问题讨论】:

    标签: wcf post


    【解决方案1】:

    您的问题是您将 JSON object 传递给操作,但该操作需要 JSON string。如果我正确理解 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(而不是字符串)。这样你应该能够基本上接受任何输入。您可能还需要一个内容类型映射器。您可以在http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx 找到有关此方案的更多信息。

    【讨论】:

    • 好的,我把它改成bare,写了一个数据合约。但是当我在我的 android 模拟器中发送 JSON 对象时,什么也没有发生。我在 receiveData 方法中添加了一个断点。
    • 什么都没有发生?您在拨打电话时收到的HttpResponse 实例上得到了什么?
    • 没什么,因为在我得到响应之前,我得到了 ConnectTimeoutException。
    • 您可以尝试做的一件事是在服务器上enable tracing 看看是否有任何异常可以解释问题。
    猜你喜欢
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2018-08-03
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多