Hi, I am working on migrating from ASP.NET Web API to ASP.NET Core and re-wrote the below code using .net core but run into errors where as this same code works fine in ASP.NET Web API.
public class DataController : Controller
{
private IList<string> errors = new List<string>();
[HttpPost]
[Route("data/import", Name = "DataImport")]
public IActionResult Post()
{
var rawdata = ConvertToByteArray(Request.Body);
var rdrec = Encoding.UTF8.GetString(content).Split(new string[] { Environment.NewLine, @"\r" }, StringSplitOptions.None).ToList();
importdata(rdrec);
if (errors.Count == 0)
return Ok("POST");
else
return Ok(errors);
}
private void importdata(IList<string> lines)
{
string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString;
var message = "";
var Data = from line in lines
let data = line.Split(',')
select new filedata
{
ID = data[0],
Type = data[1],
Status = data[2],
Description = data[3]
};
using (SqlConnection sqldbConnection = new SqlConnection(connectionString))
{
sqldbConnection.Open();
foreach (var i in Data)
{
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[testImport] ([ID], [Type], [Status], [Description]) VALUES (@ID, @Type, @Status, @Description)", sqldbConnection))
{
cmd.Parameters.AddWithValue("@ID", i.ID);
cmd.Parameters.AddWithValue("@Type", i.Type);
cmd.Parameters.AddWithValue("@Status", i.Status);
cmd.Parameters.AddWithValue("@Description", i.Description);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
message = ex.StackTrace;
return (message);
}
}
}
}
private byte[] ConvertToByteArray(Stream stream)
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
Primarily run into errors at two places
1) Reading raw datastream. The issue I am running into is when I test the post method I get success message but data is not getting inserted in the table. When I debug it I see it reading just the header line but not the rows. My guess is its throwing me off at the below line of code.
var rawdata = ConvertToByteArray(Request.Body);
2) Setting the database connectionstring from appsettings.json previously I was able to fetch the connectionstring fine from web.config file.
string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString;
What I have tried:
To get the sql database connectionstring at runtime I am putting the connectionstring in the appsettings.json file but not sure how to call it in the Controller.
appsettings.json
{
"SQLDB": {
"SQLDBCONN": {
"MySQLConnStr": "Data Source=datamartprd.multco.us\\SQLSVR,2505;Initial Catalog=BISTG_CLOUD_QAT;User Id=dbsql_bidm__googleapps_qry;Password=wf#Gd5MZw9hJ;"
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SQLDBCONN")));
}