WCF POST Params不以JSON格式返回

时间:2013-06-17 17:14:01

标签: c# json wcf azure

我正在开发一个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;
                }
            }
        }
    }

请帮帮我!已经一整天了!

2 个答案:

答案 0 :(得分: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)
    {
    }
}

BTW,您发布到服务的json字符串应该像

接口

中定义的

{"Lc":{"AccountID":null,"NRIC":"nric1","Password":"password1"}}

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

否则会导致credentials参数为空,credentials.NRIC会抛出异常

答案 1 :(得分: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; 

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