System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')' 2 - c#

This line is causing an error in my project:
options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
Error:
System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')'
I have read through a bunch of similar problems online and I cannot find a change that works. It seems that the parameter inside UseSqlServer() is returning null. This leads me to believe that I have a configuration mistake.
Here is my code for my Startup and json files:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ContosoUniversity.Data;
namespace ContosoUniversity
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
services.AddDatabaseDeveloperPageExceptionFilter();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=(***;Database=***;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"AllowedHosts": "*"
}
Any assistance is appreciated. Thanks.

You are trying to get a connection string called SchoolContext but you only have one in the config called DefaultConnection. So either fix your code:
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Or fix your config:
{
"ConnectionStrings": {
"SchoolContext": "Server=....."
},
// etc...

Related

ASP.NET Core WebAPI 6 cannot get value from configuration, how to fix?

I am trying migration source code of a ASP.NET Core 3.x to version 6.x . Source code https://www.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api//download/JWTTokenPOC.zip .
Current project, I am using ASP.NET Core WebAPI 6 . My appsettings.json
{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "qualified.domain.name",
"TenantId": "22222222-2222-2222-2222-222222222222",
"ClientId": "11111111-1111-1111-11111111111111111",
"Scopes": "access_as_user",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"ConnectionStrings": {
"DefaultConnection": "Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;"
}
},
"AllowedHosts": "*",
"AppSettings": {
"Key": "986ghgrgtru989ASdsaerew13434545439",
"Issuer": "atul1234"
}
}
File applications.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"AllowedHosts": "*",
"AppSettings": {
"Key": "986ghgrgtru989ASdsaerew13434545435",
"Issuer": "atul1234"
},
"ConnectionStrings": {
"DefaultConnection": "Server=127.0.0.1;Port=5432;Database=foo;User Id=postgres;Password=postgres;"
}
}
}
My Program.cs has error
using acc7.Data;
using JWTTokenPOC.Helper;
using JWTTokenPOC.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
using System.Configuration;
using AuthenticationService = JWTTokenPOC.Service.AuthenticationService;
namespace acc7
{
public class Program
{
public IConfiguration Configuration { get; }
public Program(IConfiguration configuration)
{
Configuration = configuration;
}
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
// builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql("Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;"));
builder.Services.AddControllers();
builder.Services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<JWTTokenPOC.Service.IAuthenticationService, AuthenticationService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
// set global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
app.Run();
}
}
}
How to fix?
You can't inject services in Program.cs using constructor. This is where the application starts, dependency injection container is not created yet. Instead you can access configuration using builder.Configuration:
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
var app = builder.Build();
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#access-configuration-in-programcs

Asp.net API not appearing

i am trying to make an angular application that takes an api made from asp.net core but while making the api , it didn't work and appear as planned and didn't know where was the problem...
I made an asp.net core web app.
This is the student.cs file made in the model folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI101.Model
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public bool Pass { get; set; }
}
}
This is the studentmanager also in model folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI101.Model
{
public class StudentManager
{
public List<Student> GetResults()
{
List<Student> oList = new List<Student>();
var r = new Random();
for(int i = 0; i < 10; i++)
{
var x = new Student();
x.ID = i;
x.Name = String.Format("Name{0}", i, ToString());
x.Pass = (r.Next() % 2 == 0);
oList.Add(x);
}
return oList;
}
}
}
This is startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI101
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
This is the code that should return aaaaa
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI101.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
[Route("mariam")]
public string test()
{
return "aaaaa";
}
}
}
I tried to launch the code and it didn't work as planned o the link:https://localhost:5001/api/Student/mariam
While running the application on the previous link it appeared like that:
browser status after running
This is the lanchsettings.json:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:40854",
"sslPort": 44361
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebAPI101": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "api/Student/mariam",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
The configuration is missing AddControllers and MapControllerRoute calls. Checkout the example below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebAPI101
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseDefaultFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"default",
"api/{controller}/{action=Index}");
});
}
}
}

How to connection multiples databases MySQL with C#?

I am building an ASP.NET web API application, and I'm stuck in a problem... :/
I have appsettings.json to configure mysql connection:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"CoinConnection": "server=127.0.0.1;user id=root;password=root;port=3306;database=coin_db;Allow User Variables=True;",
"UserConnection": "server=127.0.0.1;user id=root;password=root;port=3306;database=user_db;Allow User Variables=True;"
}
}
I have Startup.cs to execute the service to connect mysql:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication2
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<AppDb>(_ => new AppDb(Configuration["ConnectionStrings:CoinConnection"]));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I have AppDb.cs to receive a string and connect in database coin_db in mysql:
using System;
using MySqlConnector;
namespace WebApplication2
{
public class AppDb : IDisposable
{
public MySqlConnection Connection { get; }
public AppDb(string connectionString)
{
Connection = new MySqlConnection(connectionString);
}
public void Dispose() => Connection.Dispose();
}
}
I don't know how I can do to connect the second database (user_db)... I've tried everything and I don't know how to do it.
You don't need a second connection, if it is the same server.
Simply add the database name before the table name
SELECT a.*,b.* FROM coin_db.table1 a INNER JOIN user_db.tabl2 b ON a.id P= b.id
Mysql can identify so, whichtable you mean.
two connection is possible see here Choose one of many Internet connections for an application
Have you tried using a different AppDb implementation for each db?
Then you can access them via dependency injection in your routes.
public class UserDb : AppDb
{
public UserDb(string connectionString)
: base(connectionString)
{}
// ...
}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<AppDb>(_ => new AppDb(Configuration["ConnectionStrings:CoinConnection"])); // TODO: use CoinDb class and make AppDb class abstract
services.AddTransient<UserDb>(_ => new UserDb(Configuration["ConnectionStrings:UserConnection"]));
services.AddControllers();
}

Integrating Ocelot 16.0 with ASP.Net Core 3.1 not working as I need to use Swagger with Ocelot

I have used Ocelot with Asp.Net Core 2.1 and its working but when using with Asp.Net Core 3.1 it is not working at all. In my opinion, it is not picking up the "ocelot.json" file. Following is my Program.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ApiGateway
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"ocelot.{hostingContext.HostingEnvironment.EnvironmentName}.json")
.AddEnvironmentVariables();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
And below is Startup.cs file :
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace ApiGateway
{
public class Startup
{
private IConfiguration configuration;
public Startup(IConfiguration configuration)
{
this.configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context => {
await context.Response.WriteAsync("API GATEWAY FUNCIONANDO");
});
});
app.UseOcelot().Wait();
}
}
}
Below is ocelot.Development.json file :
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/TestApi/api/test",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "80"
}
],
"UpstreamPathTemplate": "/getTest"
},
{
"DownstreamPathTemplate": "/TestMicroS/api/values",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "82"
}
],
"UpstreamPathTemplate": "/getValues"
}
],
"GlobalConfiguration": {
}
}
I have referred all above configuration from YouTube but it is not working. Local website is working but when I try to hit the UpStream path it is giving me localhost not found 404 error. Please assist me to resolve this.
Thanks in advance.
Try renaming ReRoutes to Routes in your JSON file.
I had similar issue recently,
apart from the ReRoutes to Routes , I had another problem in
In the ocelote.json file
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7083
}
The port number which I had configured was for https and not for http in launchsettings.json file of the project
"applicationUrl": "https://localhost:7083",
I changed it to https to make it work
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7083
}

Ambiguity between 'Startup.Configuration' and 'Startup.Configuration'

I get an error of "Ambiguity between 'Startup.Configuration' and 'Startup.Configuration'" on my startup class. I don't know what I have done to cause this issue. All I did was create a DBContext class and this error occured. Please see my code below:
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using IssueTracker.Data;
namespace IssueTracker
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// Enabling CORS
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
// Connect to the Database
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.getConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("EnableCORS");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
ApplicationDbContext
using IssueTracker.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace IssueTracker.Data
{
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}
// Creating the roles
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<IdentityRole>().HasData(
new { Id = "1", name="Admin", NoralizeName = "ADMIN" },
new { Id = "1", name="Customer", NoralizeName = "CUSTOMER" },
new { Id = "1", name="Moderator", NoralizeName = "MODERATOR" }
);
}
public DbSet<ProductModel> Products { get; set; }
}
}
Could you please tell me what is wrong here? Thank you.
I had the same error and simply closing and reopening my IDE (Visual Studio Code) solved it. I hope it helps
One reason for this error might be that you have accidently made a copy of Startup.cs file.
I coppied solution file for backup purposes then I got that error. When I delete the backup file problem solved.

Categories