如何返回数据表格式wcf休息服务?

时间:2016-06-02 06:00:05

标签: c# wcf client-server

我想将数据表格式的wcf rest服务返回到c#表单,但是在将datatable表单服务器返回给客户端时会出现错误。

  

无法从传输连接读取数据:远程主机强行关闭现有连接。

3 个答案:

答案 0 :(得分:0)

也许,问题是,数据表的大小太大了。序列化数据表非常复杂,因此响应长度或深度可能会溢出。您可以尝试配置它。

请参阅this post

但我的建议是:不要通过网络服务回复数据表:)你不应该知道,谁在另一边听。

答案 1 :(得分:0)

我已经解决了这个问题。 当我们返回数据表格式wcf rest Services时,数据表会出现序列化问题。

           to avoid this problem convert datatable in to json stirg,and return this string to client side.
               on the client side convert this string to datatable.

服务器端代码:

       public string GetAssetRegisterDataTableBySp(ParameterDto parameters)
    {
        string jsonString="";
        string query = string.Format("SELECT * FROM ReportDisplaySetting where Display= 'true'");
        var DisplayColumnSetting = repositoryReportDisplaySetting.ExecuteRawQuery<ReportDisplaySetting>(query).ToList();
        List<string> selectedColumn = DisplayColumnSetting.Select(C => C.ColumnName).ToList();
        string columnOfString = (string.Join(",", selectedColumn.Select(x => x.ToString()).ToArray()));

        List<string> locationIds = new List<string>();
        if (parameters.locationId == 0)
        {
            locationIds = repository.All<CompanyLocationMaster>().AsEnumerable().Where(x => x.CompanyID == parameters.companyId && x.IsActive == true).Select(x => x.LocationID.ToString()).ToList();
        }
        string locationString = "";
        if (locationIds.Count() > 0)
        {
            locationString = string.Join(",", locationIds.ToArray());
        }
        else
        {
            locationString = parameters.locationId.ToString();
        }
        var report = new AssetrakRepository<AssetRegisterReport>();
        DataTable taggingReport = report.GetAssetRegisterReportBySP(parameters.companyId, locationString, columnOfString);
        string strColumns = columnOfString;
        var JSONString = new StringBuilder();
        if (taggingReport.Rows.Count > 0)
        {
            JSONString.Append("[");
            for (int i = 0; i < taggingReport.Rows.Count; i++)
            {
                JSONString.Append("{");
                for (int j = 0; j < taggingReport.Columns.Count; j++)
                {
                    if (j < taggingReport.Columns.Count - 1)
                    {
                        JSONString.Append("\"" + taggingReport.Columns[j].ColumnName.ToString() + "\":" + "\"" + taggingReport.Rows[i][j].ToString().Replace(","," ") + "\",");
                    }
                    else if (j == taggingReport.Columns.Count - 1)
                    {
                        JSONString.Append("\"" + taggingReport.Columns[j].ColumnName.ToString() + "\":" + "\"" + taggingReport.Rows[i][j].ToString().Replace(",", " ") + "\"");
                    }
                }
                if (i == taggingReport.Rows.Count - 1)
                {
                    JSONString.Append("}");
                }
                else
                {
                    JSONString.Append("},");
                }
            }
            JSONString.Append("]");

        }
        jsonString=JSONString.ToString();


        return jsonString;
    }

客户端代码:

        DataTable dt = ConvertJSONToDataTable(jsonString);


       protected DataTable ConvertJSONToDataTable(string jsonString)
    {
        DataTable dt = new DataTable();
        //strip out bad characters
        string[] jsonParts = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");

        //hold column names
        List<string> dtColumns = new List<string>();

        //get columns
        foreach (string jp in jsonParts)
        {
            //only loop thru once to get column names
            string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
            foreach (string rowData in propData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string n = rowData.Substring(0, idx - 1);
                    string v = rowData.Substring(idx + 1);
                    if (!dtColumns.Contains(n))
                    {
                        dtColumns.Add(n.Replace("\"", ""));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error Parsing Column Name : {0}", rowData));
                }

            }
            break; // TODO: might not be correct. Was : Exit For
        }

        //build dt
        foreach (string c in dtColumns)
        {
            dt.Columns.Add(c);
        }
        //get table data
        foreach (string jp in jsonParts)
        {
            string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
            DataRow nr = dt.NewRow();
            foreach (string rowData in propData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string n = rowData.Substring(0, idx - 1).Replace("\"", "");
                    string v = rowData.Substring(idx + 1).Replace("\"", "");
                    nr[n] = v;
                }
                catch (Exception ex)
                {
                    continue;
                }

            }
            dt.Rows.Add(nr);
        }
        return dt;
    }

答案 2 :(得分:-1)

以下是针对您的问题的解决方案,请参阅此博客并按照以下步骤操作我遇到的类似问题Remote Host Connectivity以及返回数据表的示例代码段。

[WebMethod]
    public DataTable GetBankdtls(string pm_Action, string pm_bankid, string pm_name, string pm_Accno, string pm_branch, string pm_VidStr)
    {
        MySqlParameter[] param = new MySqlParameter[6];
        DataTable dt = new DataTable("Bank");
        cn = new MySqlConnection(conn);
        try
        {
            string query = "DML1_getbank_Sp";
            cmd = new MySqlCommand(query, cn);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandTimeout = 120;
            cmd.Parameters.AddWithValue("pm_Action", pm_Action);
            cmd.Parameters.AddWithValue("pm_bankid", pm_bankid);
            cmd.Parameters.AddWithValue("pm_name", pm_name);
            cmd.Parameters.AddWithValue("pm_Accno", pm_Accno);
            cmd.Parameters.AddWithValue("pm_branch", pm_branch);
            cmd.Parameters.AddWithValue("pm_VidStr", pm_VidStr);               
            cn.Open();
            da.SelectCommand = cmd;
            da.Fill(dt);
            return dt;
        }
        catch (MySqlException ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Connection.Close();
            cn.Close();
        }
    }

并确保您的连接应该打开,最后应该关闭。