更改从wcf服务方法返回的json对象包装器名称

Roh*_*agh 4 c# asp.net wcf json wcf-binding

我创建了一个WCF 3.5应用程序,其方法名称TestMe如下所示:

 [OperationContract]
        [WebInvoke(UriTemplate = "/Login", Method = "POST",
            BodyStyle = WebMessageBodyStyle.Wrapped,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        MyDictionary<string, string> TestMe(string param1, string param2);
Run Code Online (Sandbox Code Playgroud)

MyDictionary使用以下链接创建:https://stackoverflow.com/a/7590189/546033

这里的一切都很好.但问题是从以下实现的方法返回数据时:

MyDictionary<string, string> success = new MyDictionary<string, string>();
success["desc"] = "Test";
return success;
Run Code Online (Sandbox Code Playgroud)

它返回以下json:

{"TestMeResult":{"desc":"Test"}}
Run Code Online (Sandbox Code Playgroud)

而我需要的是:

{"success":{"desc":"Test"}}
Run Code Online (Sandbox Code Playgroud)

success对象名称在哪里.有什么办法可以解决这个问题?

Raj*_*han 6

您可以使用MessageParameter属性.

控制请求和响应参数名称的名称.

[OperationContract]
    [WebInvoke(UriTemplate = "/Login", Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)] 
    [return: MessageParameter(Name = "success")]
    MyDictionary<string, string> TestMe(string param1, string param2);
Run Code Online (Sandbox Code Playgroud)