使用c#将json字符串数据传递给Rest服务(POST方法) [英] Pass json string data to Rest service (POST Method) using c#

查看:66
本文介绍了使用c#将json字符串数据传递给Rest服务(POST方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我必须将动态Json字符串传递给WCF Rest服务。这里的输入/输出都应该是Json格式。我正在使用服务器端代码传递我的数据。这是我的代码



在testpage.aspx.cs页面

< pre lang =c#> string json = { \sjSonData \:[{
+ \log_Id \\ \\:0,
+ \user_Id \:1249,
+ \session_key \:\dvnoewcdw \ ,
+ \app_id\:1,
+ \app_version \:\1.2.7 \,
+ \app_isOnline \:true,
+ \app_dateTimeZone \:\1997-07-16T19:20:30 + 01:00\\,
+ \log_typeId \:1,
+ \log_description\:\valid \
+ },
+ {
+ \\ \\log_Id \:1,
+ \ user_Id \:1249,
+ \session_key \: \dvnoewcdw \,
+ \app_id\ :1,
+ \app_version \:\1.2 .7 \,
+ \app_isOnline \:true ,
+ \app_dateTimeZone \:\1997-07 -16T19:20:30 + 01:00 \
+ }] };

const string url = http://localhost/RestServiceImpl.svc/jsoninputdata;

// 创建对我们需要调用的URL的HTTP请求
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
request.ContentType = application / json; charset = utf-8; // 将内容类型设置为JSON
request.Method = POST; // 发布HTTP POST

使用 var streamWriter = new StreamWriter(request.GetRequestStream()))
{
// 发起请求
JavaScriptSerializer serializer = new JavaScriptSerializer();
var resToWrite = serializer.Deserialize< Dictionary< string,object>>(json);
streamWriter.Write(restoWrite);
streamWriter.Flush();
streamWriter.Close();
}

// 获取回复。
WebResponse response = request.GetResponse();
var streamReader = new StreamReader(response.GetResponseStream());
var result = streamReader.ReadToEnd();





我是WCF服务的新手。我不知道如何将此数据传递给Rest服务。在这里,我的输入数据每次通话都有所不同。



休息服务代码



 [ServiceContract] 
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = POST
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = jsoninputdata)]
string jsoninputdata(List<字典< string,object>> rData);
}

public class RestServiceImpl:IRestServiceImpl
{
public jSonResponseData jsoninputdata(List< Dictionary< string,object>> rData)
{
string json = JsonConvert.SerializeObject(rData);
// 在这里做我的东西.....
return ojSonRes; // 这里我需要返回下面提到的输出
}
}





我需要返回如下数据(输出),



条件1: 如果两者都保存在db中没有任何错误,



{sjSonData:[{成功:true}]}



条件2: 假设任何一个数据都无法保存在数据库中



{sjSonData:[{log_Id:1,success:false},{log_Id:2,success:true}] }



现在我得到的结果如下,



{sjSonData:{}}



我做错了什么!!!!!还请解释我在web.config文件中要做的所有更改。

解决方案





我找到了解决这个问题的方法。请参考以下链接 DotNetCodeForU



谢谢,

D.Rajasekaran


In my project i have to pass dynamic Json string to WCF Rest service. Here both Input / Output should be in Json format. I am using server side code to pass my data. Here is my code

In testpage.aspx.cs Page

string json = "{\"sjSonData\":[{"
                             + "\"log_Id\" : 0,"
                             + "\"user_Id\" : 1249,"
                             + "\"session_key\" : \"dvnoewcdw\","
                             + "\"app_id\" : 1,"
                             + "\"app_version\" :\"1.2.7\","
                             + "\"app_isOnline\" : true,"
                             + "\"app_dateTimeZone\" : \"1997-07-16T19:20:30+01:00\","
                             + "\"log_typeId\" : 1,"
                             + "\"log_description\" : \"valid\""
                         + "},"
                         + "{"
                             + "\"log_Id\" : 1,"
                             + "\"user_Id\" : 1249,"
                             + "\"session_key\" : \"dvnoewcdw\","
                             + "\"app_id\" : 1,"
                             + "\"app_version\" : \"1.2.7\","
                             + "\"app_isOnline\" : true,"
                             + "\"app_dateTimeZone\" : \"1997-07-16T19:20:30+01:00\""
                             +"}]}";

const string url = "http://localhost/RestServiceImpl.svc/jsoninputdata";

       //create an HTTP request to the URL that we need to invoke
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);                
            request.ContentType = "application/json; charset=utf-8"; //set the content type to JSON
            request.Method = "POST"; //make an HTTP POST

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                //initiate the request
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var resToWrite = serializer.Deserialize<Dictionary<string, object>>(json);
                streamWriter.Write(restoWrite);
                streamWriter.Flush();
                streamWriter.Close();
            }

            // Get the response.
            WebResponse response = request.GetResponse();                
            var streamReader = new StreamReader(response.GetResponseStream());                
            var result = streamReader.ReadToEnd();



I am new to WCF service. I don't know how to pass this data to Rest service. Here my input data has been differed every call.

Rest Service code

[ServiceContract]
 public interface IRestServiceImpl
 {
   [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "jsoninputdata")]
    string jsoninputdata(List<Dictionary<string, object>> rData);
 }    

 public class RestServiceImpl : IRestServiceImpl
 {    
      public jSonResponseData jsoninputdata(List<Dictionary<string, object>> rData)
      {       
          string json = JsonConvert.SerializeObject(rData);
          //Do my stuff here.....    
          return ojSonRes; // Here i need to return my output mentioned below
      }
  }



And i need to return data (output) like below,

Condition 1: If both saved in db without any error,

{"sjSonData":[{ "success":true }]}

Condition 2: Suppose any one data failed to save in database then

{"sjSonData":[ { "log_Id":1, "success":false }, { "log_Id":2, "success":true } ]}

Now I am getting result like,

{"sjSonData":"{}"}

Am i doing anything wrong!!!!! and also please explain what are all changes i have to do in web.config file.

解决方案

Hi,

I found solution for this problem. Please refer the following link DotNetCodeForU

Thanks,
D.Rajasekaran


这篇关于使用c#将json字符串数据传递给Rest服务(POST方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆