将JSON对象发布到WCF服务对象始终为null

时间:2013-01-22 08:40:50

标签: c# asp.net ajax wcf wcf-data-services

我在'post'.am上遇到问题时,用户对象总是为空。我在我的智慧结束并且已经研究了好几天,所以如果有任何想法,请帮助!提前致谢

我的Jquery看起来像这样

$(document).ready(function () {
        $("#register").click(function (e) {
            e.preventDefault(); //stop the submit event for the submit button
            var Name = $("#register_username").val();
            var Email = $("#register_email").val();
            var Password = $("#register_password").val();
            var Contact = $("#register_contactNumber").val();
            var Adress = "Seteelte Town";
            var chkUserType = document.getElementById("identity_type_2").checked;
            var userinfo = { "request": { "Action": { "Address": Adress, "Children": [], "CityId": 0, "Email": Email, "HomeUser": chkUserType, "ImagePath": "", "IpAdress": "", "IsActive": false, "LastLogin": "", "Name": Name, "Password": Password, "PhoneNumber": Contact, "ProfileHit": 0, "ShowEmail": false, "ShowPhoneNumber": false, "SubscribeNews": false, "UserID": 0}} };

            alert("Input: " + JSON.stringify(userinfo));
            $.ajax({
                type: "POST",
                url: '/Services/Membership.svc/AccountAdd',
                data: JSON.stringify(userinfo),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert(data.Result);
                },
                error: onError
            });
        });
    });

我的WCF的C#代码是

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Membership : IMembership
    {

        public SMProcessResponse<bool> AccountAdd(SMProcess<User> request)
        {
            return new SMProcessResponse<bool>(MembershipController.AccountAdd(request.Action));
        }
}

流程请求的C#代码是

[DataContract(Namespace = "")]
    public class SMProcess<T> : BaseRequest
    {

        public SMProcess(T obj)
        {
            // TODO: Complete member initialization
            this.Action = obj;

        }
        [DataMember]
        public T Action { get; set; }
    }

这是我的Web.config

<configuration>
        <connectionStrings>
   //here is connection string
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>
  <system.serviceModel>
    <services>
      <service name="SelectionMall.Services.Membership">
        <endpoint address="" behaviorConfiguration="Services.webHttpBehavior" binding="webHttpBinding" contract="SelectionMall.Services.IMembership" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="Services.webHttpBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

2 个答案:

答案 0 :(得分:1)

您需要将正确的WebInvoke属性应用于WCF操作。看看你的JSON请求,我相信它应该像

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json))]
SMProcessResponse<bool> AccountAdd(SMProcess<User> request)

请注意,需要包装的正文样式(或WrappedRequest),以便将输入JSON视为包装的(即参数名称将是传入JSON的属性)。

除此之外,您可能会遇到SMProcess<T>反序列化的问题,因为它没有任何参数较少的构造函数。

无论如何,我建议你从简单的服务声明(和实现)开始,例如

public SMProcessResponse<bool> AccountAdd(User request)
{
   return new SMProcessResponse<bool>(MembershipController.AccountAdd(request));
}

然后开始添加额外的嵌套等。

答案 1 :(得分:1)

您的JSON请求应该是这样的

[OperationContract]
        [WebInvoke(UriTemplate = "AccountAdd", Method = "POST")]
        SMProcessResponse<bool> AccountAdd(SMProcess<User> request);

和您的JSOn数据

var userinfo = { "request": { "Action": { "Address": Adress, "Children": [], "CityId": 0, "Email": "waheed@gmail.com", "HomeUser": true, "ImagePath": "C:/Waheed.jpg", "IpAdress": "192.168.1.3", "IsActive": true, "LastLogin": "\/Date(1358852299323+0500)\/", "Name": "Waheed Iqbal", "Password": "111111", "PhoneNumber": "+923226270150", "ProfileHit": 10, "ShowEmail": true, "ShowPhoneNumber": true, "SubscribeNews": true, "UserID": 1}} }
编辑Web.config后

<behavior name="Services.webHttpBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" defaultBodyStyle="WrappedRequest" />
        </behavior>

欢呼声