【问题标题】:How to returning WCF Service POST response as JSON如何以 JSON 形式返回 WCF 服务 POST 响应
【发布时间】:2021-09-08 12:28:31
【问题描述】:

我已经使用 POST 请求创建了 WCF 服务。

 [OperationContract]
        [WebInvoke(Method = "POST",
         ResponseFormat = WebMessageFormat.Json,
         RequestFormat = WebMessageFormat.Json,
         //  BodyStyle = WebMessageBodyStyle.Wrapped,
         UriTemplate = "/UpdateRCFOnline"
         )]
        String UpdateRCFOnline(RCFOnline rcf_class);

  public string UpdateRCFOnline(RCFOnline rcf_class)
    {
        string success = string.empty;
                
        try
        {
            //POST data to DB
            success = "Update Success";
        } catch(Exception ex){
            success = "Update Failed, " +ex.message;
        }
        
    return success;
    
    }

如何使这个 POST 请求以 JSON 形式返回“成功”。因为如果我在 Fiddler 中尝试过这项服务。我在“原始”选项卡而不是 JSON 上收到消息。

【问题讨论】:

    标签: c# wcf rest


    【解决方案1】:

    试试下面

    public object UpdateRCFOnline(RCFOnline rcf_class)
    {     
        try
        {
            //POST data to DB
            return new {
               success = "Update Success";
            }
        } catch(Exception ex){
            return new {
               success = "Update Failed, " +ex.message;
            }
        }
    
    }
    

    这样你将返回一个将被反序列化为 json 字符串的对象。

    注意。还要检查是否可以将 return data type 设置为 json

    【讨论】:

    • 如果能定义返回数据对象类就更好了
    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多