Asked by:
ASP.net web api migration to ASP.net core

Question
-
User-1396990745 posted
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); //ASP.net core; error //var rawdata = ConvertToByteArray(Request.Content.ReadAsStreamAsync().Result); //ASP.net web api 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 = @"Data Source=localhost;Initial Catalog=TEST_DB;Integrated Security=True"; string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString; // Added this to appsettings.json file and get null reference error in ASP.net core; works fine in ASP.net web api 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.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;
Thank you in advance.
Monday, July 9, 2018 6:20 PM
All replies
-
User36583972 posted
Hi vscsl,Primarily run into errors at two placesYou can include the detailed exception messages. This will help us quickly analyze your problem.
You can use the Configuration API provides to configure an ASP.NET Core web app based on a list of name-value pairs. Configuration is read at runtime from multiple sources. Name-value pairs can be grouped into a multi-level hierarchy
Best Regards,
Yong Lu
Tuesday, July 10, 2018 8:43 AM -
User1100692814 posted
Hi,
For connection string, you should try:
{ "ConnectionStrings": { "YourNameHere": "Server=YourServer;Database=YourDb;Trusted_Connection=True;" }, } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<YourDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("YourNameHere"))); }
.NET Core uses the 'Options Pattern' for Configuration. Check https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration
Hope this helps.
/D
Tuesday, July 10, 2018 8:49 AM -
User-1396990745 posted
Hi Yohann Lu, The trouble I have is when I run 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 but not the rows.
I guess its throwing me off here...
var rawdata = ConvertToByteArray(Request.Body);
Thank you.
Tuesday, July 10, 2018 4:01 PM -
User-1396990745 posted
Hi Dave Winchester, I will work on making changes per your response.
Thank you.
Tuesday, July 10, 2018 4:02 PM -
User36583972 posted
Hi vscsl,The trouble I have is when I run 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 but not the rows.From your code above, I cannot see any code you have used to save rawdata to the database.
Besides, when you debug steps by steps, Whether the rawdata get the correct values?
Best Regards,Yong Lu
Wednesday, July 11, 2018 5:39 AM -
User-1396990745 posted
Hi Yohann Lu, When I debug my code I see header line from the file showup but not the record lines.
var rdrec = Encoding.UTF8.GetString(content).Split(new string[] { Environment.NewLine, @"\r" }, StringSplitOptions.None).ToList(); importdata(rdrec);//see the header line but no record lines
Thank you.
Wednesday, July 11, 2018 5:28 PM -
User36583972 posted
Hi vscsl,
var rdrec = Encoding.UTF8.GetString(content).Split(new string[] { Environment.NewLine, @"\r" }, StringSplitOptions.None).ToList(); importdata(rdrec);//see the header line but no record lines
You may need to check the content and try to get the correct rdrec values.
Best Regards,
Yong Lu
Monday, July 16, 2018 10:05 AM