public class Startup
{
public void Configuration(IAppBuilder app)
{
System.Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
}
}
I want to add the Code"System.Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); to my program.cs file in my ASP.net MVC project. The code example was written with the old version of ASP.net MVC. The new version does not have a startup.cs. My question is how do I implement the code in my program.cs file that it completes the task.
just add this in appsettings.json
"AppSettings": {
"ASPNETCORE_ENVIRONMENT": "Development",
}
if you are trying to use another version then what I had understood. refer to this Microsoft Documentation here
Related
I'm just learning Entity Framework Core 3.1. I wondering why all learning contents learn it using ASP.Net Core!! So I decide to test some of the codes on a Class Library along withConsole Application. This is my very simple class library code:
public class ApplicationDbContext : DbContext
{
private static readonly string ConnectionString = "Server=.;Database=Northwind;Trusted_Connection=True;";
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<NimaCategory> NimaCategories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new NimaCategoryConfig());
}
}
I faced many strange errors for creating Migration but strangest is I must write all of these line of codes to my Console Application:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello EF Core")
}
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
webBuilder => webBuilder.UseStartup<Startup>());
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
=> services.AddDbContext<ApplicationDbContext>();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
}
}
and the problem is IHostBuilder and ConfigureWebHostDefaults are for ASP.Net Core and it's dependency injection engine. So based on the below link I change my csproj file:
IHostBuilder does not contain a definition for ConfigureWebHostDefaults
Now I can't run my console application because It's nature has changed and converted to Web project. Then I add a window application and I can't add these codes for configurations:
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
webBuilder => webBuilder.UseStartup<Startup>());
and:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
=> services.AddDbContext<ApplicationDbContext>();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
}
}
I have some questions about this problems:
Why EF Core is restricted to ASP.Net Core? Are all the projects in the world written with ASP.Net Core?
Does anyone have experience working with EF core along with Windows Application or Console project and help to solve the issues?
Thanks
You can use EF Core everywhere.
Make a Console application project then install these packages
https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/3.1.9
https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/3.1.9
and put your connection string in OnConfiguringMethod.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=serverName;Database=dbName;Trusted_Connection=True;MultipleActiveResultSets=True");
}
and voila you can learn ef core in console app. they just teach ef core with ASP.NET Core because of UI.
and i think Julie Lerman Teaches EF Core in Console app, you can use Pluralsight platform for EF Core tutorials.
Here are some answers, as well as what I use to get my EF Core working.
Why EF Core is restricted to ASP.Net Core? Are all the projects in the world written with ASP.Net Core?
It's not restricted to ASP.Net Core, EF Core and Core itself is simply a console application. And no all projects in the work are not build with ASP.NET Core --- However, due to it's flexibility Microsoft is dropping support for all other versions of .Net. Meaning the next Release of .Net will actually be .NetCore. If you are building for a normal .Net application, it might be better to use EF 6 instead of Core. Core just allows crossplatform capabilities.
Does anyone have experience working with EF core along with Windows Application or Console project and help to solve the issues?
Well yes, also all Core applications are Console Projects. So if you are able to do it in a windows application you are able to do it in Core.
But now I will show you what I do. I work for a company and use EF core on multiple projects, my basic formula looks like this:
Nuget Packages:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Relational
Here is the code in the Startup file. Note it will look slightly different than yours because I put my Dbcontext in a different project than my entry point.
public void ConfigureServices(IServiceCollection services)
{
// Add the SQL db conneciton
/*
AddSQLContext is just a function in a different project. Not Needed
*/
services.AddSQLContext(options => options.UseSqlServer(
// This is simply the connection stirng
Configuration.GetConnectionString("SqlConnection"),
// We add a migration assembly only if the EF core DbContext is in another project
actions => actions.MigrationsAssembly("My.Other.Project.Assembly")
));
}
My code for calling the Context is in another project. I like to keep it seperate. But you don't have to do that.
Here are the Nuget packages I use, But I think the Tools and Design are only neccecary when doing a CodeFirst approach (building Database from EF core instead of Scaffolding):
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools
public static class ServiceCollectionExtentions
{
/*
SqlContext is my own custom context similar to your [ ApplicationDbContext ]
*/
public static IServiceCollection AddSQLContext(this IServiceCollection services, Action<DbContextOptionsBuilder> options) => services
.AddDbContext<SqlContext>(options);
}
public class SqlContext : DbContext
{
public SqlContext(DbContextOptions options)
: base(options){}
...
}
The solution is very simple: just add default constructor for the ApplicationDbContext:
public ApplicationDbContext()
{
}
I have a .net core application running in Windows and Linux as well (I use .net core runtime >= 2.1). To get better insights I'd like to expose a metrics endpoint (simple HTTP GET endpoint) for Prometheus publishing some internal stats of my application.
Searching through the WWW and SO I always ended up on using asp.net core. Since I only want to add a quite simple HTTP GET endpoint to an existing .net core app it seems a little bit overkill, to port the whole application to asp.net.
The alternative I already considered was to write my own handler based on HttpListener. This is quite straight forward when it comes to a simple HTTP endpoint, but since all information I found regarding SSL and Linux was, this is not supported at the moment and I should go with asp.net. (https://github.com/dotnet/runtime/issues/33288#issuecomment-595812935)
So I'm wondering what I missunderstood! Am I the only one?
Is there already a good library providing a simple http(s) server for .net core?
EDIT: [SOLVED]
As #ADyson mentioned in the comments below the existing application does not need to be ported to asp.net core!
Project files generated with dotnet new web in version 2.1 automatically added
references to "Microsoft.AspNetCore.App" and "Microsoft.AspNetCore.Razor.Design"
When I referenced my asp.net core project from a .net core project and executed the code hosting the web service I ended up with an System.IO.FileNotFoundException stating it "Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core'".
Microsoft.AspNetCore.App is a metapackage also referencing said Microsoft.AspNetCore.MVC! Thus, the executing assembly also has to reference this metapackage. This observation missled me that using asp.net core renders my whole application to be built around Microsoft.AspNetCore.App.
After removing these references and adding only a reference to "Microsoft.AspNetCore" everything works as expected.
After checking the generated project files from dotnet new web in version 3.1 these references were not added. This is not a problem for folks using newer versions of dotnet!
As mentioned by #ADyson, OWIN is the way to go. You can easily self-host a HTTP endpoint in your existing application. Here is a sample to self-host it in a .Net Core 3.1 console application. It exposes a simple endpoint listening on port 5000 for GET requests using a controller. All you need is to install the Microsoft.AspNetCore.Owin Nuget package.
The code files structure is as follows:
.
├── Program.cs
├── Startup.cs
├── Controllers
├── SayHi.cs
Program.cs
using Microsoft.AspNetCore.Hosting;
namespace WebApp
{
class Program
{
static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://*:5000")
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
Startup.cs
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace WebApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
SayHi.cs
using Microsoft.AspNetCore.Mvc;
namespace WebApp.Controllers
{
public class SayHi : ControllerBase
{
[Route("sayhi/{name}")]
public IActionResult Get(string name)
{
return Ok($"Hello {name}");
}
}
}
Then a simple dotnet WebApp.dll would start the app and web server.
As you can see, the sample uses Kestrel. The default web server. You can check Microsoft's related documentation.
For more configuration and routing options you can check Microsoft's documentation.
One option is to use EmbeddIo
https://unosquare.github.io/embedio/
I find the documentation is not always the best, especially as they recently upgrade and many samples etc. are not valid. But you can get there!
You can self host a REST API like this:
WebServer ws = new WebServer(o => o
.WithUrlPrefix(url)
.WithMode(HttpListenerMode.EmbedIO))
.WithWebApi("/api", m => m
.WithController<ApiController>());
this.Cts = new CancellationTokenSource();
var task = Webserver.RunAsync(Cts.Token);
Then define your API Controller like this.
class ApiController : WebApiController
{
public ApiController() : base()
{
}
[Route(HttpVerbs.Get, "/hello")]
public async Task HelloWorld()
{
string ret;
try
{
ret = "Hello from webserver # " + DateTime.Now.ToLongTimeString();
}
catch (Exception ex)
{
//
}
await HttpContext.SendDataAsync(ret);
}
}
Project files generated with dotnet new web in version 2.1 automatically added references to "Microsoft.AspNetCore.App" and "Microsoft.AspNetCore.Razor.Design" which, when referenced by a .net core project and executed ended up with an System.IO.FileNotFoundException stating it "Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core'".
Creating a project with dotnet new web in version 3.1 does not reference these, thus the project can be referenced and executed from a .net core application.
-> Using asp.net core is a viable solution for me (again)!
I am able to integrate the Swagge UI in my web api using Swashbuckle. I also want to explore the swagger codegen feature. Can somebody help in - how I can integrate swagger codegen into my web api project? Or do I need to download any tool? I want to be able it to host the codegen and pass the json/raml form specs to generate client in .net core.
I am not able to find enough docs on above.
EDIT : I want to know how I can host codegen in my WEBAPI.
Thanks!
Now, you can use Nswag. There are several code generator utilities - UI, Console, msbuild.
You should install "Swashbuckle.AspNetCore.Swagger" nuget package by right click your project and click manage nuget packages.
Then you should add these codes into your project startup place eg. Program.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
app.UseMvc();
}
It seems like you just want to generate C# from the OpenApi specification (your Swagger implementation provides the input) of your API.
To generate code (e.g. C#) from the OpenApi spec file of your API, you can do something like this:
java -jar .\openapi-generator-cli-5.0.0-beta3.jar generate -i https://localhost:xxxx/api/v1/swagger.json -g csharp
You have to download the OpenApi Generator Jar. Alternatively you can upload your code to a web generator. But I would always run this locally; you never know where your code ends up.
I must develop on an existing project (There is no documentation or any developers)
that targets framework 4.5
There is tasks like this which return return Ok or BadRequest
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (userModel == null)
{
return BadRequest();
}
//......there is other codes
return Ok("it is ok");
}
and in startup.cs there is some configuration
public void Configuration(IAppBuilder app)
{
var kernel = SetupNinject();
ConfigureOAuth(app);
SetupSignalR(kernel, app);
ConfigureCors(app);
SetupWebAPI(kernel, app);
SetupStaticFiles(app);
}
I am asp.net mvc developer and not familiar with the above code. In my previous projects there is no async Task and startup.cs with app configuration.
I can open project with visual studio 2012 and rebuild or run succesful. There is no console.
Is this project asp.net core?
I get the impression that you are trying to determine what framework the above code uses.
Is this project asp.net core?
Short Answer: NO
Not so short answer:
IHttpActionResult is part of Action Results in Asp .Net Web API 2 and is associated with results returned from ApiController
That Configuration method with IAppBuilder is part of Microsoft OWIN Components.
I have asp.net core library project.
I want to add connection string to it. I don't have startup class in this. Where I need to place connection string and how to fetch it?
In dotnet core you can manage configuration using json files, which is one in many ways to configure your application.
According to the dotnet core configuration documentation you can simply do (copied from link reference)
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
// Add NuGet <package id="Microsoft.Extensions.Configuration" and
// <package id="Microsoft.Extensions.Configuration.Json"
// .NET Framework 4.x use the following path:
//.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), #"..\.."))
public class Program
{
static public IConfigurationRoot Configuration { get; set; }
public static void Main(string[] args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
Console.WriteLine($"option2 = {Configuration["option2"]}");
Console.WriteLine(
$"option1 = {Configuration["subsection:suboption1"]}");
}
}
Then in your appsettings.json file you can add:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}
And access it in code using Configuration.GetConnectionString("BloggingDatabase")
I can recommend also reading the dotnet core documentation regarding connection strings
EDIT: As the commentors mention on your post, don't add connection strings and config files to your library code - do this from your console application or the web application!
Additional forms of configuration for dotnet core includes user secrets, environment variables and perhaps XML files or other forms of storage, as pointed out in the comments