0

我正在开发一个 android 应用程序,并试图通过 web 服务发送数据。由于某种原因,我的 WCF 没有以 JSON 格式发送数据,我已将绑定设置为 webHttpBinding, ResponseFormat = WebMessageFormat.Json

这是我的 IService 代码:

    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "LoginMobile",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    LoginCredentials GetLogin(LoginCredentials Lc);

[DataContract]
public class LoginCredentials
{
    [DataMember(Name = "AccountID")]
    public string AccountID
    {
        get;
        set;
    }
    [DataMember(Name = "NRIC")]
    public string NRIC
    {
        get;
        set;
    }
    [DataMember(Name = "Password")]
    public string Password
    {
        get;
        set;
    }
}

我的服务:

    public LoginCredentials GetLogin(LoginCredentials credentials)
    {
        string strConnectionString = ConfigurationManager.ConnectionStrings["PCSDB"].ConnectionString;
        string strCommandText = "Select AccountID from Account Where NRIC=@NRIC AND Password=@Password";

        using (SqlConnection sqlConnection = new SqlConnection(strConnectionString))
        {
            sqlConnection.Open();

            using (SqlCommand sqlCommand = new SqlCommand(strCommandText, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@NRIC", credentials.NRIC);
                sqlCommand.Parameters.AddWithValue("@Password", credentials.Password);

                int queryResult = sqlCommand.ExecuteNonQuery();
                SqlDataReader reader = sqlCommand.ExecuteReader();

                if (reader.Read())
                {
                    credentials.AccountID = reader["AccountID"].ToString();
                    return credentials;
                }
                else
                {
                    credentials.AccountID = "0";
                    return credentials;
                }
            }
        }
    }

请帮我!一整天都在这!

4

2 回答 2

1

我测试了你的代码。您的方法定义是正确的,并按预期返回 json。

据我所知,您的方法返回 XML 的唯一方法是您的方法抛出异常。(您可以通过将其添加return credentials为方法的第一行来测试它)

您可以通过编写如下自定义错误处理程序来覆盖此行为(抛出异常时返回 xml)。

只需在属性[JsonErrorHandlerBehavior]后添加到您的类[ServiceContract]

public class JsonErrorHandlerBehaviorAttribute : Attribute, IErrorHandler, IServiceBehavior
{
    public bool HandleError(Exception error)
    {
        //Log the error
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var fd = new JsonFaultDetail();
        fd.Message = error.Message;

        fault = Message.CreateMessage(version, string.Empty, fd, new DataContractJsonSerializer(fd.GetType()));

        var jsonFormatting = new WebBodyFormatMessageProperty(WebContentFormat.Json);
        fault.Properties.Add(WebBodyFormatMessageProperty.Name, jsonFormatting);

        var httpResponse = new HttpResponseMessageProperty()
        {
            StatusCode = HttpStatusCode.InternalServerError,
        };

        fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
        return;
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            if (dispatcher.BindingName.Contains("WebHttpBinding"))
                dispatcher.ErrorHandlers.Add(this);
        }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

顺便说一句,您发布到服务的 json 字符串应该像

{"Lc":{"AccountID":null,"NRIC":"nric1","Password":"password1"}} 如接口中定义的,

不是 {"LoginCredentials":{"AccountID":null,"NRIC":"nric1","Password":"password1"}}

否则这将导致credentials参数为空并credentials.NRIC抛出异常

于 2013-06-17T18:55:24.543 回答
0

当我使用 JSon 时,我在我的 WebMethod 上使用了类似的东西。

//references. //
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Services;
    using System.Web.Script.Services;
    using System.Data.SqlClient;
    using System.Web.Security;
    using Newtonsoft.Json;

// returning. //
    return JsonConvert.SerializeObject(credentials);

在我的客户端,我使用了:-

// client side reference. //
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>

// storing returned data. //
    var jsondata = $.parseJSON(data.d);
    credentials = jsondata.credentials; 

不确定这是否是您正在寻找的。需要更多解释。

于 2013-06-17T17:15:45.880 回答