简体   繁体   中英

How to return datatable form wcf rest services?

I want to return datatable form wcf rest service to c# form,but following error raised when returning datatable form server to client.

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Maybe, that the problem is, that the size of the datatable is too big. A serialized datatable is pretty complex, so the response length or depth can overflow. You can try to config this.

See this post

But my suggestion is: don not respond with a datatable through webservice :) You should not know, who on the other side listens.

I have got Solution to this problem. When we return datatable form wcf rest Services then serialization problem occur with datatable.

           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.

Server Side Code:

       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;
    }

Client Side Code:

        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;
    }

Here is the solution for your problem please refer this blog and follow these steps i experienced similar issue Remote Host Connectivity and sample code snippet for returning data table.

[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();
        }
    }

and make sure your connection should be open and at the end it should close.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM