在WCF服务中接收POST数据 [英] Receiving POST data in WCF Service

查看:104
本文介绍了在WCF服务中接收POST数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了许多教程,但是无法在我的项目中运行它.我几乎没有发送数据的GET服务,但是它们运作良好,但是在接收数据时遇到了问题.如果有人可以告诉我失败的地方,而不是发布一些链接,我将不胜感激. :) 当我尝试在浏览器中调用服务时,出现错误:不允许使用方法.但是我认为这只是第一个错误.

I read many tutorials but I could not get this running for my project. I made few GET services which send data and they work great, but I have problems receiving the data. I would really appreciate it if someone could tell me where I fail, instead of posting some links. :) When I try to call the service in my browser I get the error: Method not allowed. But I Think this is just the first error.

这是我的代码. 首先,我将Android称为服务的代码:

Here is my code. First the code in Android where I call the service:

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:

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:

RestServiceImpl.cs:

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

Web.config:

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>

推荐答案

您的问题是您要向操作传递JSON 对象,但是操作需要JSON 字符串.如果我正确理解Java代码,这就是您要发送的内容:

Your problem is that you're passing a JSON object to the operation, but the operation is expecting a JSON string. If I understand correctly the Java code, this is what you're sending:

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

这不是JSON字符串.

Which is not a JSON string.

您可以做几件事.第一种选择是修改操作,使其不采用字符串,而采用等效于该对象的数据协定.

There are a couple of things you can do. The first alternative is to modify the operation not to take a string, but to take a data contract which is equivalent to that object.

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

The code would look something like the one below. Notice that you should also change the body format to Bare (instead of 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 (而不是字符串).这样,您应该基本上可以接受任何输入.您可能还需要内容类型映射器.您可以在

Another alternative, if the "schema" of the data changes every time, would be to take the input as a Stream (not a String). That way you should be able to accept basically any input. You may also need a content type mapper. You can find more information about this scenario at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx.

这篇关于在WCF服务中接收POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆