Buongiorno,
sto provando a connettere l'applicazione ASP.NET Core MVC che sto realizzando ad un DB MySql.
Di seguito la configurazione del file "appsettings.json":
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionString": {
"DefaultConnection": "server=localhost;port=3306;database=aspnetcoremvc;user=root;password=xxxxxxxx"
}
}
Di seguito la configurazione del file "Startup.cs":
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
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.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Add(new ServiceDescriptor(typeof(MusicStoreContext), new MusicStoreContext(Configuration.GetConnectionString("DefaultConnection"))));
}
Di seguito la configurazione del file "MusicStoreContext.cs" (posizionato nella root del progetto):
public string ConnectionString { get; set; }
public MusicStoreContext(string connectionString)
{
this.ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<Album> GetAllAlbums()
{
List<Album> list = new List<Album>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("select * from Album where id < 10", conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Album()
{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
ArtistName = reader["ArtistName"].ToString(),
Price = Convert.ToInt32(reader["Price"]),
Genre = reader["genre"].ToString()
});
}
}
}
return list;
}
Questo il controller che fa il richiamo della view (che poi mi genera errore):
[Area("Admin")]
public class AdminController : Controller
{
public IActionResult Index()
{
MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(AspNetCoreMVCCMS.MusicStoreContext)) as MusicStoreContext;
return View(context.GetAllAlbums());
}
}
Questo è l'errore che mi viene segnalato dalla view:
MySql.Data.MySqlClient.MySqlException (0x80004005): Host '192.168.1.180' is not allowed to connect to this MariaDB server
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at AspNetCoreMVCCMS.MusicStoreContext.GetAllAlbums() in C:\Users\Alessio\Dropbox\VS2017\AspNetCoreMVC-CMS\AspNetCoreMVC-CMS\MusicStoreContext.cs:line 30
at AspNetCoreMVCCMS.Areas.Admin.Controllers.AdminController.Index() in C:\Users\Alessio\Dropbox\VS2017\AspNetCoreMVC-CMS\AspNetCoreMVC-CMS\Areas\Admin\Controllers\AdminController.cs:line 17
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Ho notato che quando viene richiamato questo metodo del file "MusicStoreContext.cs" (durante l'esecuzione di ConfigureServices di Startup.cs):
public MusicStoreContext(string connectionString)
{
this.ConnectionString = connectionString;
}
il valore di "connectionString" è nullo.
Spero che qualcuno possa aiutarmi e vi ringrazio in anticipo.
Saluti,
Alessio.