use static files in aspnet core 2 - c#

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?

Related

Why am I getting this error in ASP.NET Core 6 C#?

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

IdentityBuilder does not contain a definition for 'AddEntityFrameworkStores

I am using .netcore 3.1. While using the following code:
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.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
///using AspNetCore3JWT.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Jwt.Data;
namespace Jwt
{
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.AddControllers()
.AddNewtonsoftJson();
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
// 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 got this error:
I just upgraded a project to .net core 3.1, and had to change the following line from
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<DBContext>();
To
services.AddDefaultIdentity<ApplicationUser>().AddUserStore<DBContext>();
In addition to installing the package Microsoft.AspNetCore.Identity.EntityFrameworkCore per serpent5's comment, I also had to install the package Microsoft.AspNetCore.Identity.UI.
Make sure you inherit from IdentityDbContext not DbContext only

Entity Framework .Net Core using VS2019 Community on Mac OS don't works

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

How to make IOutputFormatter work in an ASP.NET Core Web API application?

I am in the process of learning C#/.NET right now and currently I am working on learning using C# in an ASP.NET Core Web API application. Right now I am having trouble using IOutputFormatter within the Startup.cs file of my project because it is currently giving me this error right now:
Startup.cs(39,25): error CS0246: The type or namespace name 'IOutputFormatter' could not be found (are
you missing a using directive or an assembly reference?)
[/Users/steelwind/HardWay/c#and.NET/PracticalApps/NorthwindService/NorthwindService.csproj]
Startup.cs(41,55): error CS0246: The type or namespace name 'OutputFormatter' could not be found (are
you missing a using directive or an assembly reference?)
[/Users/steelwind/HardWay/c#and.NET/PracticalApps/NorthwindService/NorthwindService.csproj]
Here is what my Startup.cs file looks like right now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
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.EntityFrameworkCore;
using Packt.Shared;
using static System.Console;
namespace NorthwindService
{
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)
{
string databasePath = Path.Combine("..", "Northwind.db");
services.AddDbContext<Northwind>(options => options.UseSqlite($"Data Source{databasePath}"));
services.AddControllers(options =>
{
WriteLine("Default output formatters:");
foreach(IOutputFormatter formatter in options.OutputFormatters)
{
var mediaFormatter = formatter as OutputFormatter;
if (mediaFormatter == null)
{
WriteLine($" {formatter.GetType().Name}");
}
else // OutputFormatter class has SupportedMediaType
{
WriteLine(" {0}, Media types: {1}",
arg0: mediaFormatter.GetType().Name,
arg1: string.Join(", ", mediaFormatter.SupportedMediaType));
}
}
})
.AddXmlDataContractSerializerFormatters()
.AddXmlSerializerFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
// 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 already tried adding "using Microsoft.AspNetCore.Mvc.Formatters;" however this created another error on "SupportedMediaTypes" at line 51 of the Startup.cs file.

Add an implementation of 'IDesignTimeDbContextFactory' to the project?

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

Categories