Linqpad 6 supports .Net Core.
When I create a new empty .Net Core API solution in visual studio , I get a simple template with a simple demo controller.
When I run it in visual studio it uses a command-line server (kestrel) to run the project :
So I wanted to see if I can run this project in Linqpad 6.
So I've installed all nugets and copied the code to Linqpad :
https://i.stack.imgur.com/lwRyU.png
void Main()
{
CreateWebHostBuilder(new string[] { "" }).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// 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();
}
app.UseMvc();
}
}
I do see that it is now listening :
But calls to http://localhost:5000/api/values do get acked , but without the json value response from controller :
Question:
How can I get Linqpad to return the value from the controller? ( a simple json)
There's a difference in the way LINQPad executes code that could account for this not working.
Being a scripting tool, LINQPad wraps everything in a class (otherwise, the Main method would have nowhere to live). So ValuesController is actually ends up as a nested type, UserQuery.ValuesController, and this could potentially upset the routing API.
For such situations, LINQPad has the ability to extract all nested types and move them outside UserQuery (using the Roslyn API). To enable this, add the following to the start of your query:
#LINQPad nonest
Something else to consider is that a default MVC project includes an appsettings.json file. Should this be required for your code in LINQPad, you need to create such a file and add a reference to it (when you reference to a non-binary file, LINQPad copies it into the output folder, which is exactly where appsettings.json needs to be).
Edit: There's now a checkbox in the Query Properties dialog to add ASP.NET Core references to a query in LINQPad 6. This pulls the assemblies straight from the shared framework folder, and is easier than finding the right NuGet packages.
Related
Hello everyone my name is Taniguchi and i learning asp.net core and I managed to create a migration but when I used the Update-Database command show me the following error: "
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No migrations configuration type was found in the assembly 'WebApplication1'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
my database:
public class MimicContext : DbContext
{
public MimicContext(DbContextOptions<MimicContext> options) : base(options)
{
}
public DbSet<Palavra> Palavras { get; set; }
}
my startup:
public class Startup
{
// 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 https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MimicContext>(opt =>
{
opt.UseSqlite("Data Source=Database\\Mimic.db");
});
services.AddMvc(options => options.EnableEndpointRouting = false);
}
// 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.UseMvc();
}
}
How can i configure a migration to the assembly ?
Have you enabled migrations in your project? If you didn't than use Enable-Migrations. I think that it could be the problem.
Before running the update command in PMC first enable it. For more details view this link here
Small mistake, but good learning for me after spending more than one day painful effort. I hope this will be the good learning for others too.
I have added two NuGet packages of: EntityFramework, and Microsoft.EntityFrameworkCore which is my mistake.
Just adding NuGet package for Microsoft.EntityFrameworkCore will do all the required work.
I have a .net core web api application that I have recently tried to debug (in VS2017) on a new computer (after a long hiatus from working on the app). I also upgraded the .net core from 1.1 to 2.2. However, it no longer seems to route at all, even to the ValuesController which I left in for testing purposes, nor with just using localhost (I had been testing it with my local ip address). I've created another web api project (which routes fine) in the same solution and have compared code, config files etc; I've simplified my own code to extreme matching the working web api code:
public class Program {
public static void Main(string[] args) {
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
And I've stripped out all but the bare bones of Startup.cs
public partial class Startup {
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
...
And made sure my my launchSettings.json also matched my test web api (have tried launching with both the service directly, or via IISExpress). Relevent bit for direct launch:
"profiles": {
"MyWebApiService": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:8080;https://localhost:44385"
}
}
But when it launches, although it first calls http://localhost:8080/api/values, and the redirect to https://localhost:44385/api/values works fine, the call to https://localhost:44385/api/values returns http code 404.
Is there any way to see what is going on in the routing? What it's looking for and where?
In your code supplied I don't see AddHttpsRedirection in ConfigureServices. Please add:
services.AddHttpsRedirection(options =>
{
options.HttpsPort = 443;
});
Please refer to: Enforce HTTPS in ASP.NET Core
Similar problem to WebApi giving 404 whilst debugging; works when published but I hadn't checked the published version. Also, my Sdk as set in the <Project> node in the .csproj file was:
Microsoft.NET.Sdk.Web
as it should be. However, I did have the <PreserveCompilationContext> there and explicitly set to false, which appears to have worked fine prior to v. 2.1. Setting this to true was the solution here:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
...
"MVC 2.1.0 requires compilation context to be available. Compilation context tells it if a library references MVC which is used as a filter to skip assemblies that are deemed unlikely to have controllers." See ASP.NET Core 2.1.0 breaks attribute-routed endpoints in applications targeting Microsoft.NET.Sdk #8388
Note this issue is in all of Microsoft.AspNetCore.App and Microsoft.AspNetCore.All versions 2.1.0, 2.1.1, 2.1.2 and 2.1.3.
I have a scenario where we have a "standardised startup" for many small AspNet Core websites.
A seemingly obvious solution to achieve this is to refactor the Startup.cs class into a separate common assembly (as Infrastructure.Web.Core.Startup). We then have each small AspNet Core website reference it the common assembly and use that startup class instead:
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder CreateWebHostBuilder( string[] args )
{
return new WebHostBuilder()
.UseKestrel()
.ConfigureServices( collection => { } )
.UseContentRoot( System.IO.Directory.GetCurrentDirectory() )
.UseStartup<Infrastructure.Web.Core.Startup>(); //.UseStartup<Startup>();
}
Somehow, this breaks attribute routing in the sense that the routes are not hit. No errors, but not routing. The moment I copy the class back into the website project (with the exact same code) it works again.
As a test, if I wrap the Startup.cs class in the common library in a local startup class (like below), it also works:
public class Startup
{
private readonly Infrastructure.Web.Core.Startup _startup;
public Startup( IConfiguration configuration )
{
_startup = new Infrastructure.Web.Core.Startup( configuration );
}
public IConfiguration Configuration => _startup.Configuration;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices( IServiceCollection services )
{
_startup.ConfigureServices( services );
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure( IApplicationBuilder app, IHostingEnvironment env )
{
_startup.Configure( app, env );
}
}
If I had to take a guess, it's probably something to do with the Dependency Injection.
Does anyone have any suggestions?
FYI: It's using typical AspNet Core 2.1 projects
UPDATE
Incidentally, if I use inheritance it also works but the derived class must be in the same project as the website. I guess it seems obvious, but thought I include that information for completeness sake:
public class Startup : Infrastructure.Web.Core.Startup
{
public Startup( IConfiguration configuration ) : base(configuration)
{
}
}
You can fix this by adding the following statement to your services in your Startup.cs method.
services.AddApplicationPart(typeof(AnTypeInTheOtherAssembly).Assembly);
This will tell the View/Controller Discovery to also check for the new location. Your Project which contains the Startup.cs file would be the Startup Project, and all the others would be just references and libraries or similar.
As of .Net Core 3 you can use something called Razor Class Libraries, see the MSDN. This will automatically add this your Controllers and Views to the discovery, it also has debugging support and will work just as a normal Class Library would.
I am trying to get an ASP.NET Core 2 with EntityFramework Core 2.0 application up and running. As part of it, also looking to start using Migrations to manage data model changes.
Here is my appsettings.json file where I am storing connection strings. For keeping things simple here, I left the user/pwd open. In real scenario, encryption will be used. Main goal is to use two separate connection strings. One for Application usage, where the user account TestAppServiceAccount will be used only to perform reads/writes (DML operations only). Another one called DbChangeServiceAccount for applying migrations (DML + DDL operations).
{
"SqlServerMigrationsConnection": "Server=SqlServerInstance;Database=TestDb;User Id=DbChangeServiceAccount; Password=xyz$123;",
"SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=TestAppServiceAccount; Password=xyz$123;"
}
Here is how my Startup.cs is setup. Based on my understanding, looks like both application and Migrations are going to depend on the same connection string that is passed in startup.cs to AddDbContext method.
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.AddMvc();
var userServiceSqlConnection = Configuration["SqlServerAppConnection"];
services.AddDbContext<UserContext>(optiopns => optiopns.UseSqlServer(userServiceSqlConnection));
}
// 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();
}
app.UseMvc();
}
}
Just wondering how do I pass a different connection strings, one that will be used purely for application and another one for just applying migrations?
After posting this question, I realized that, I could make use of multi environment setup.
So for migrations I will have a separate environment that will be used to manage CI/CD activities. I feel like this is a deployment concern,
So I could simply create appsettings.migrations.json or something similar and fall back to use just one connection string for both Application and Migrations. And my Startup.cs AddDbContext parameters will stay same.
My appsettings.development.json will look like
{
"SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=TestAppServiceAccount; Password=xyz$123;"
}
My appsettings.migrations.json will look like
{
"SqlServerAppConnection": "Server=SqlServerInstance;Database=TestDb;User Id=DbChangeServiceAccount; Password=xyz$123;"
}
How to manage multiple environments in asp.net core from Microsoft has more details.
I'm starting a new project in VS 2015.
File -> New -> Project -> ASP.NET Web Application -> ASP.NET 5 Templates -> Web API
A project is initialized. I would assume that if I run the project with IIS Express a service would be available.
It runs through the startup methods.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
But then it crashes. I don't know how to implement global error handling.
I looked at this example.
But when I try to use System.Net.Http or System.Web.Http.ExceptionHandling they can't be found.
I also noticed that through intellisense it says Core 5.0 is no available.
Here is my project.json as requested.
{
"version":"1.0.0-*",
"compilationOptions":{
"emitEntryPoint":true
},
"dependencies":{
"Microsoft.AspNet.IISPlatformHandler":"1.0.0-rc1-final",
"Microsoft.AspNet.Mvc":"6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel":"1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug":"1.0.0-rc1-final"
},
"commands":{
"web":"Microsoft.AspNet.Server.Kestrel"
},
"frameworks":{
"dnx451":{
"frameworkAssemblies":{
"System.Web":"4.0.0.0"
}
},
"dnxcore50":{
}
},
"exclude":[
"wwwroot",
"node_modules"
],
"publishExclude":[
"**.user",
"**.vspscc"
]
}
Try to open Visual Studio Administrator Mode
I guess it depends on what is crashing - it's not clear from your description what crashes, when it crashes and how it crashes.
You can use UseExceptionHandler and UseDeveloperExceptionPage extension methods to configure an error handling page. This article describes it in more details.
If the exception happens during startup you may need to use UseCaptureStartupErrors extension method (it was recently renamed to CaptureStartupErrors).
Also, you already have logging enabled - the logs may also have some useful information. If you can't see logs because you log to the console consider logging to a file.
If this is IIS/IISExpress crashing check event log.
What is your runtime version ?
Maybe you can try scaffolding your application with the AspNet Yeoman generator and compare the files.
Personally I prefer to use the scaffolder as it is often up to date.
Hope this helps !