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.
Related
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
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 new to GraphQL, when I try to upgrade .net core version from 2.2 to 3.0
I got problem about UI display on /graphql page when using UseGraphiQl
API is working normally but the UI is display incorrect.
I googled for find out solutions, but nothing really helpful.
Here is my config for graphql:
services.AddRazorPages().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
app.UseGraphiQLServer(new GraphiQLOptions());
app.UseGraphiQl("/graphiql", "/graphql");
app.UseEndpoints(x =>
{
x.MapControllers();
});
Any help is greatly appreciated, thanks.
Finally, I find out the solution:
services.AddRazorPages().AddNewtonsoftJson();
As part of the work to improve the ASP.NET Core shared framework, Json.NET has been removed from the ASP.NET Core shared framework.
To use Json.NET in an ASP.NET Core 3.0 project:
Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.
Update Startup.ConfigureServices to call AddNewtonsoftJson.
Ref: https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#jsonnet-support
I'm not sure if they are changing anything in .net core version 3.0 but you can view my blog here
I'm using GraphQL.Server.Ui.Playground
Below is minial config you can see
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddGraphQL(x =>
{
x.ExposeExceptions = true; //set true only in development mode. make it switchable.
})
.AddGraphTypes(ServiceLifetime.Scoped);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)
{
app.UseGraphQL<DataSchema>();
app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
The result is the same with GraphiQl
Edit: This is because Newtonsoft.Json is change in .Net Core 3. You can view my answer here
ASP.NET Core 3.0 [FromBody] string content returns "The JSON value could not be converted to System.String."
How do you add and use an SQLite database in an ASP.NET Core web application, using EntityFramework 7 ?
I dived into ASP.NET Core the moment I heard about it and created my first web application, I suddenly had a bunch of data that I wanted to store and SQLite seemed like the obvious choice.
Since I wanted it to stay with my application, keep it lightweight, simple and avoid setting up a separate database.
So how would one go about creating an SQLite database in ASP.NET Core?
ASP.NET Core - now formerly known as ASP.NET MVC 6
EntityFramework Core - now formerly known as EntityFramework 7
Update: November 4th, 2016.
Reformatting - pictures to code examples.
Info:
Keep in mind that in some code examples, code that was generated by the visual studio template have been omitted.
Update: July 11th, 2016.
.NET Core and EntityFrameWork Core version 1.0 is upon us!
So this guide deserves a little update
Step 1:
Create your application.
Step 2:
Get the necessary packages
Microsoft.EntityFrameworkCore 1.0.0
Microsoft.EntityFrameworkCore.SQlite 1.0.0
Step 3:
Create your context:
(The Context will be a class that you create)
public class DatabaseContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=MyDatabase.db");
}
}
Step 4:
Add your context to your services:
(Located in your Startup class)
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}
Step 5:
Create your database on startup, by adding it to the startup method
(Located in the Startup class)
public Startup(IHostingEnvironment env)
{
using(var client = new DatabaseContext())
{
client.Database.EnsureCreated();
}
}
Et Voíla!
Now you will be able to use SQLite in your ASP.NET Core applications.
The old guide still applies regarding how you create your models as well as using your database context.
Update: May 28th, 2016.
.NET Core RC2 and EntityFramework Core RC1 have been released.
They have improved and simplified the steps for setting up SQLite.
But I'm experiencing some trouble with it and can't replicate it, because of an error with the Newtonsoft.Json library and NuGet.
I recommend sticking to the RC1 libraries if you want to do this, for now!
Step 1:
Create your ASP.NET web application
Step 2:
Go to Tools -> Nuget Packet Manager -> Manage Nuget Packages for Solution.
Search for EntityFramework.SQLite and check the Include prelease box.
Install the package
Step 3: Creating a context
Create a context class for your database.
Call it whatever you want, but let's go with something that's customiary, like MyDbContext.
Make your new class inherit the DbContext class and override the OnConfiguring method and define your connection like so:
public class MyDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "MyDb.db" };
var connectionString = connectionStringBuilder.ToString();
var connection = new SqliteConnection(connectionString);
optionsBuilder.UseSqlite(connection);
}
}
Step 4:
Go to the Startup.cs and make sure your database is created at the start of your web application:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
using (var db = new MyDbContext())
{
db.Database.EnsureCreated();
db.Database.Migrate();
}
}
Secondly we need to add the service:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<MyDbContext>();
}
Step 5: Defining your Models
Create your models and go to MyDbContext.cs and add a new property for each of your new models (given that you want a table for each!)
Here's an example:
My Model:
public class Category
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string UrlSlug { get; set; }
}
Adding it to my context:
public class MyDbContext : DbContext
{
public DbSet<Category> Categories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "MyDb.db" };
var connectionString = connectionStringBuilder.ToString();
var connection = new SqliteConnection(connectionString);
optionsBuilder.UseSqlite(connection);
}
}
Step 6: Using the the context
Go to your HomeController and add a new field to your controller.
private readonly MyDbContext _myDbContext = new MyDbContext();
And use it in an ActionResult by passing it to the returned view:
(Now lets assume we have a category in our database)
public IActionResult Index()
{
var category = _myDbContext.Categories.First();
return View(category);
}
So by going to your Index view, you can use our imaginary data from the database. By defining a model in the top of your view like so:
#model MyNameSpace.Models.Category
#{
ViewData["Title"] = "Hey Ho! SO!";
}
<div class="page-header">
<h1>#ViewData["Title"]</h1>
</div>
<div class="container">
#Model.Title
</div>
Now by starting our web application and going to the assigned address we should see a default html page with a fancy bootstrap header, showing this on the page:
The second line is (or would be) the title of our first category in our database.
Entity Framework 7 Docs
This is my first Q&A - if you have any input or something that needs clarifying don't hesitate to comment.
This is a very basic example of how to implement an SQLite database into an ASP.NET Core MVC web application.
Do note that there is several ways to set the connection string for the database, how to use the context and that EntityFramework 7 is still a prerelease
If you want to create an ASP.NET Core web application using SQLite for the database, I highly recommend using Yeoman to scaffold the app for you. You need to first install .NET Core 1.1 SDK (Visual Studio 2015 seems to only include SDK versions 1.0.0 and 1.0.1 at the moment). You then need to install Node.js which comes with npm and then install the following npm packages: yo and generator-aspnet. Then all you have to do is run yo aspnet and answer a few questions.
C:\Development>yo aspnet
? ==========================================================================
We're constantly looking for ways to make yo better!
May we anonymously report usage statistics to improve the tool over time?
More info: https://github.com/yeoman/insight & http://yeoman.io
========================================================================== Yes
_-----_ ╭──────────────────────────╮
| | │ Welcome to the │
|--(o)--| │ marvellous ASP.NET Core │
`---------´ │ generator! │
( _´U`_ ) ╰──────────────────────────╯
/___A___\ /
| ~ |
__'.___.'__
´ ` |° ´ Y `
? What type of application do you want to create? Web Application
? Which UI framework would you like to use? Bootstrap (3.3.6)
? What's the name of your ASP.NET application? WebApplication
Afterwards, you will get the following response:
Your project is now created, you can use the following commands to get going
cd "WebApplication"
dotnet restore
dotnet build (optional, build will also happen when it's run)
dotnet ef database update (to create the SQLite database for the project)
dotnet run
Run dotnet restore, dotnet ef database update, and then dotnet run and go to localhost:5000 to make sure the project is running.
Now you can open the project in Visual Studio 2015 (assuming you're on Windows) or Visual Studio Code.
The great thing about this is that Startup.cs, project.json, and appsettings.json files are setup to use SQLite. Also, a SQLite database is created for you:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
}
project.json:
{
"Microsoft.EntityFrameworkCore.Sqlite": "1.1.0",
"Microsoft.EntityFrameworkCore.Sqlite.Design": {
"version": "1.1.0",
"type": "build"
}
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=WebApplication.db"
}
}
Your SQLite database will be located in bin/Debug/netcoreapp1.0. In my case, it is located in C:\Development\WebApplication\bin\Debug\netcoreapp1.0\WebApplication.db
If you want to rename the SQLite database, modify appsettings.json file and run dotnet ef database update.
To learn more about using SQLite database with .NET Core and EF Core, check out this article: .NET Core - New Database
Install Below mentioned packages
PM> Install-Package Microsoft.EntityFrameworkCore
PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite
PM> Install-Package Microsoft.EntityFrameworkCore.Tools
Create Models
Create DBContext class add SQLite connection configuration
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=DBFileName.db");
Run migration commands to start using it
PM> add-migration <MigrationName> //Ex: add-migration IntialMigration
PM> update-database
https://fullstack-lab.co.in/Sqlite-entity-framework-core-quick-start
This article provides simple steps to use SQLite with Asp.net core 3.1
In dotnet 6 :
Your DbContext constructor should look like this: (remove OnConfiguring method from your DbContext.
public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options)
{
}
and in program.cs file, add your service like this:
builder.Services.AddDbContext<PaymentDbContext>(options =>
options.UseSqlite($"Data Source={dbPath}"));
dbPath is your database address.
if you want to update your database and your dbContext file located in a different solutions don't forget to use --startup-project in dotnet ef database update command :) ex:
dotnet ef database update --startup-project ../PaymentProject.Api/PaymentProject.Api.csproj
Been fighting this one all morning. Here are the links I have been pointed to and I am still having no luck:
http://www.asp.net/visual-studio/overview/2013/release-notes-(release-candidate)
https://stackoverflow.com/a/18426574/1118218 (I did everything the accepted answer suggests)
https://stackoverflow.com/a/18419011/1118218 (same question as above, but the solution here did not work either, does not resolve the classes)
I installed the ASPNET web tools refresh. Restarted visual studio. Everything seems to build correctly except for the AccountController. It cannot find AuthenticationIdentityManager(and IdentityStore).
[Authorize]
public class AccountController : Controller
{
public AccountController()
{
IdentityManager = new AuthenticationIdentityManager(new IdentityStore());
}
public AccountController(AuthenticationIdentityManager manager)
{
IdentityManager = manager;
}
public AuthenticationIdentityManager IdentityManager { get; private set; }
}
Any idea how to get this to work? All the nuget packages related to ASP.NET Identity, Owin, EF, and MVC are updated to the latest pre-release version.
Depending on the operation you are looking to achieve here? you can get the current authentication manager via
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
which will then let you do things like
authenticationManager.SignOut();
the AuthenticationIdentityManager and the IdentityStore classes no longer exist.
The AccountController you are using seems to be generated by an older VS2013 version. The easiest way to make this work with the latest ASP.NET Identity version is by creating a new MVC Project with individual accounts using the release version of VS2013. This will create an AccountController class that is compatible with the latest ASP.NET Identity assemblies. Then replace your AccountController with the one you just generated.