Click here to Skip to main content
15,891,713 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C#
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. 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")));
}
Posted
Updated 10-Jul-18 16:47pm

1 solution

Instead of doing:

C#
services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("SQLDBCONN")));


Try:

C#
services.AddDbContext<ApplicationDbContext>(options =>    
 options.UseSqlServer(Configuration.GetConnectionString("SQLDB:SQLDBCONN:MySQLConnStr")));


The GetConnectionString() method is very clear, it will first look for the ConnectionStrings node then the name. So, don't forget to include ConnectionStrings node or the code will throw NULL exception error.

HTML
"ConnectionStrings": {
    "SQLDB": {
      "SQLDBCONN": {
        "MySQLConnStr": "your data source"
      }
    }
  }


Check my article on ASP.NET Core for an example: Getting Started with Entity Framework Core: Building an ASP.NET Core Application with Web API and Code First Development

And finally, check the official documenation about: Migrate from ASP.NET Web API to ASP.NET Core
 
Share this answer
 
v3
Comments
Afzaal Ahmad Zeeshan 11-Jul-18 9:30am    
5ed.
Vincent Maverick Durano 16-Jul-18 9:33am    
thank you! ;)
Member 12586110 11-Jul-18 13:04pm    
Hi Vincent Maverick Durano, Thanks very much for your response. I made changes to ConfigureServices as below.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLDB:SQLDBCONN:MySQLConnStr")));
        }


How do I call this connectionstring to dynamically change from the appsettings at runtime in the controller class?

string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString;


When using this I get an error.

Error Message:

AddDbContext was called with configuration, but the context type 'ApplicationDbContext' only declares a parameterless constructor. This means that the configuration passed to AddDbContext will never be used. If configuration is passed to AddDbContext, then 'ApplicationDbContext' should declare a constructor that accepts a DbContextOptions<applicationdbcontext> and must pass it to the base constructor for DbContext.
Vincent Maverick Durano 11-Jul-18 20:04pm    
In ASP.NET Core, you should reference the connectionString from the Configuration.GetConnectionString() method like:


string connectionString = Configuration.GetConnectionString("SQLDB:SQLDBCONN:MySQLConnStr");
Member 12586110 13-Jul-18 13:06pm    
Hi Vincent Maverick Durano, Thanks for your response. For some reason I couldn't get your solution implemented as I was running into errors.

Please find my solution below and let me know your thoughts.

Startup.cs
Hide   Copy Code
        public IConfiguration Configuration { get; }        public void ConfigureServices(IServiceCollection services)        {            services.AddMvc();            services.AddSingleton<IConfiguration>(Configuration);        }


Controller.cs
Hide   Copy Code
        public MyController(IConfiguration configuration)        {            _configuration = configuration;        }	private void importdata(IList<string> lines)        {	    string connectionString = _configuration["SQLDB:SQLDBCONN:MySQLConnStr"];	}


Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900