【问题标题】:WCF POST Params not returning in JSON formatWCF POST 参数未以 JSON 格式返回
【发布时间】:2013-06-17 17:14:01
【问题描述】:

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

请帮帮我!一整天都在做这个!

【问题讨论】:

    标签: c# json wcf azure


    【解决方案1】:

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

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

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

    只需在[ServiceContract] 属性之后将[JsonErrorHandlerBehavior] 添加到您的班级

    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 会抛出异常

    【讨论】:

    • 哦,天哪,我不敢相信我被困了一整天,因为我正在发送 LoginCredentials.. 你刚刚挽救了我生命的另一天!非常感谢!
    【解决方案2】:

    当我使用 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; 
    

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

    【讨论】:

    • 我的库中没有 JsonConvert :X
    • 现在想找,你知道我在哪里可以买到吗?
    • 在返回 JsonConvert.SerializeObject(credentials) 时,我得到“无法将类型‘字符串’隐式转换为我的 LoginCredentials”;
    • 无需手动将返回的对象序列化为Json。 WCF应该自动的。
    • 但是我的返回凭证使我的 android 应用程序崩溃,并出现 org.json.JSONException: Value
    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 2021-09-08
    • 2018-04-22
    • 2021-03-18
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多