Currently following a course from early 2018.
After running Add-Migration Initial in the Package Manager Console
This is my error message ;
Unable to create an object of type 'AppDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
The link says to add...
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace MyProject
{
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
}
to my startup.cs...
This is my startup class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using BethanysPieShop.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using WebApplication5.Models;
namespace BethanysPieShop
{
public class Startup
{
private IConfigurationRoot _configurationRoot;
public Startup(IHostingEnvironment hostingEnvironment)
{
_configurationRoot = new ConfigurationBuilder()
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
}
// 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 http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(_configurationRoot.GetConnectionString("DefaultConnection")));
services.AddTransient<ICategoryRepository, CategoryRepository>();
services.AddTransient<IPieRepository, PieRepository>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
I'm using Entity Framework Core Tools 2.1.2
AppDbContext.cs
using BethanysPieShop.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Pie> Pies { get; set; }
public class DbSet
{
}
}
}
Where/location do I implement their code in my code?
What variables do I change?
Last I remember this issue was caused because you're not using the proper WebHostBuilder Method name see this github issue
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
//.Net-core relies on Duck Typing during migrations and scaffolding
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Try putting this:
services.AddScoped(typeof(IDesignTimeDbContextFactory<BloggingContext>), typeof(BloggingContextFactory));
In Startup.cs, method ConfigureServices, below the services.AddTransient < IPieRepository, PieRepository >();
I hope you find it useful
Related
When I want to create a controller I get this error:
enter image description here
There was an error running the selected code generator:
'Unable to resolve service for type
'Microsoft.EntityFrameworkCore.Db.ContextOptions'1[DATAMain.DB] while attempting to activate 'DataMain.DB'
DB.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataMain
{
public class DB : IdentityDbContext<IdentityUser, IdentityRole, string>
{
public DB(DbContextOptions<DB> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
}
}
Be sure to have the Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore package installed.
then register the service :
using ContosoUniversity.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ContosoUniversity
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
--> services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
--> services.AddDatabaseDeveloperPageExceptionFilter();
services.AddControllersWithViews();
}
read documentation on microsoft : https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-6.0
I saw the sample ASP.NET core Web Api at following website:
https://codewithmukesh.com/blog/dapper-in-aspnet-core/
It uses the dapper for accessing SQL database with 3 class library projects. In the c# class library project named "Dapper.Infrasstructure", the ProductRepository.cs program obtains the SQL connection string from appsettings.cshtml with code shown in CODE SEGMENT 1. It also uses IServiceCollection for registering services in setup.cs (see CODE SEGMENT 2). The library project includes three packages (See CODE SEGMENT 3).
Since there is no appsettings file in any class library. how does it access the settings that is in the main project "Dapper.WebApi"? The program was build with ASP.NET core 3.1. I compiled it using .NET 5. It wors just fine. I also checked the content of its setup.cs file (see CODE SEGMENT 4) and program.cs file (see CODE SEGMENT 5).
I tried to use the similar implementation method in an ASP.NET core MVC program. It could not get the SQL connection string from appsettings contained in the main web app from the C# class library project. What makes the accessing appsettings possible in Web API but not from MVC web app?
CODE SEGMENT 1
public class ProductRepository : IProductRepository
{
private readonly IConfiguration configuration;
public ProductRepository(IConfiguration configuration)
{
this.configuration = configuration;
}
public async Task<int> AddAsync(Product entity)
{
entity.AddedOn = DateTime.Now;
var sql = "Insert into Products (Name,Description,Barcode,Rate,AddedOn) VALUES (#Name,#Description,#Barcode,#Rate,#AddedOn)";
using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
{
connection.Open();
var result = await connection.ExecuteAsync(sql, entity);
return result;
}
}
......
}
CODE SEGMENT 2
using Dapper.Application.Interfaces;
using Dapper.Infrastructure.Repository;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace Dapper.Infrastructure
{
public static class ServiceRegistration
{
public static void AddInfrastructure(this IServiceCollection services)
{
services.AddTransient<IProductRepository, ProductRepository>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
}
}
}
CODE SEGMENT 3
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.6" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
</ItemGroup>
CODE SEGMENT 4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
namespace Dapper.WebApi
{
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.AddInfrastructure();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.IncludeXmlComments(string.Format(#"{0}\Dapper.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Dapper - WebApi",
});
});
}
// 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();
#region Swagger
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CleanArchitecture.WebApi");
});
#endregion
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
CODE SEGMENT 5
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Dapper.WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
to state, I am limited with dotnet core 2, that cant change
I am trying to serve some static html page at the base of the wwwroot folder in a basic dotnet core web application but in web browsers, tested chrome and edge, they attempt to download html file as a file to be viewed in a folder.
program.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace StudentCookingWebsite
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseWebRoot("public")
.Build();
}
}
startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace StudentCookingWebsite
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
}
}
}
could someone tell me where I am going wrong?
I try to use EF core 3.1.0, could you see above:
enter image description here
I created a DBContext class:
using System;
using Microsoft.EntityFrameworkCore;
using SGC.ApplicationCore.Entity;
namespace SGC.Infrastructure.Data
{
public class ClienteContext:DbContext
{
public ClienteContext(DbContextOptions<ClienteContext> options):base(options)
{ }
public DbSet<Cliente> Clientes { get; set; }
public DbSet<Contato> Contatos { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Cliente>().ToTable("Cliente");
modelBuilder.Entity<Contato>().ToTable("Contato");
}
}
And I inserted this code in UI project Startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SGC.Infrastructure.Data;
namespace SGC.UI.Web
{
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.AddControllersWithViews();
services.AddDbContext<ClienteContext>(c => c.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, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
And the code of Program.cs class is:
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 SGC.UI.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
When I try to run de Migrations command, it throw this exception:
Unable to create an object of type 'ClienteContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
If I change the constructor of ClienteContext.cs to a parameterless constructor the migrations command works.
migration commands:
dotnet ef migrations add Inicial
I would develop an ASP.NET Core web API that redirects received HTTP API after cookie authentication.
Below my Startup.cs file:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyProject.Middlewares;
namespace MyProject.Backend
{
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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddTransient(typeof(ReverseProxyMiddleware));
}
// 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.UseHsts();
}
app.UseCookiePolicy();
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseReverseProxyMiddleware();
}
}
}
And below my middleware:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
namespace MyProject.Middlewares
{
public class ReverseProxyMiddleware : IMiddleware
{
[Authorize]
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// HTTP redirection...
}
}
}
Actually, if I try to perform an HTTP request without cookie I obtain 200 results. How can I protect my middleware?
Thanks