0

我有一个基于 WCF 的宁静服务,如下所示:(FeedbackInfo 类只有一个enum成员 - ServiceCode。)

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public List<FeedbackInfo> GetFeedbackInfoList(ServiceCode code)
{
    return ALLDAO.GetFeedbackInfoList(code);
}

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public int? CreateFeedback(FeedbackInfo feedback)
{
    return ALLDAO.CreateFeedback(feedback);
}

我将使用 jquery ajax 来调用这两个方法,如下所示:

$.ajax({
    type: "GET",
    url: "/Service/ALL.svc/GetFeedbackInfoList",
    datatype: "text/json",
    data: { "code": "Info"},
});



var feedbackInfo = { feedback: {
    ServiceCode: "Info"
}};
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/Service/ALL.svc/CreateFeedback",
    datatype: "text/json",
    data: JSON.stringify(feedbackInfo),
});

第一次调用将成功执行,而第二次调用给我一个错误:值“Info”无法解析为“Int64”类型。我想知道为什么在第二次调用中不能解析同一个枚举?仅仅因为枚举类型被用作类的成员?

编辑: FeedbackInfo 和 ServiceCode 如下所示:

public class FeedbackInfo
{
    public int ID { get; set; }
    public string Title { get; set; }
    public ServiceCode ServiceCode { get; set; }
}
[DataContract]
public enum ServiceCode
{
    [EnumMember]
    Info,
    [EnumMember]
    Error
}
4

2 回答 2

1

我已经组合了一个使用该Newtonsoft.Json库的更好的解决方案。它修复了枚举问题,也使错误处理变得更好。这是相当多的代码,所以你可以在 GitHub 上找到它:https ://github.com/jongrant/wcfjsonserializer/blob/master/NewtonsoftJsonFormatter.cs

您必须添加一些条目才能Web.config使其正常工作,您可以在此处查看示例文件: https ://github.com/jongrant/wcfjsonserializer/blob/master/Web.config

于 2016-07-12T10:43:22.760 回答
0

枚举被序列化为整数,因此您需要使用 ServiceCode: 1 (或其他),或者,在FeedbackInfo类中添加自定义属性以从给定的字符串值反序列化枚举。即,像这样:

public string ServiceCode { 
    get {
        return ServiceCodeEnum.ToString();
    }
    set {
        MyEnum enumVal;
        if (Enum.TryParse<MyEnum>(value, out enumVal))
            ServiceCodeEnum = enumVal;
        else
            ServiceCodeEnum = default(MyEnum);
    }
}

private MyEnum ServiceCodeEnum { get; set; }
于 2012-06-11T09:15:03.763 回答