Posts

Showing posts with the label Asp.Net Core

Can We Scaffold DbContext From Selected Tables Of An Existing Database

Answer : One can solve the problem by usage of dotnet ef dbcontext scaffold command with multiple -t ( --table ) parameters. It allows to specify all the tables, which needed by imported (scaffolded). The feature is described initially here. It is possible to specify the exact tables in a schema to use when scaffolding database and to omit the rest. The command-line examples that follow show the parameters needed for filtering tables. .NET Core CLI: dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -t actor -t film -t film_actor -t language -f Package Manager Console in Visual Studio: Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir Sakila -Tables actor,film,film_actor,language -f Force tag will update the existing selected models/files i...

ASP.NET Core MVC Mixed Route/FromBody Model Binding & Validation

Image
Answer : Install-Package HybridModelBinding Add to Statrup: services.AddMvc() .AddHybridModelBinder(); Model: public class Person { public int Id { get; set; } public string Name { get; set; } public string FavoriteColor { get; set; } } Controller: [HttpPost] [Route("people/{id}")] public IActionResult Post([FromHybrid]Person model) { } Request: curl -X POST -H "Accept: application/json" -H "Content-Type:application/json" -d '{ "id": 999, "name": "Bill Boga", "favoriteColor": "Blue" }' "https://localhost/people/123?name=William%20Boga" Result: { "Id": 123, "Name": "William Boga", "FavoriteColor": "Blue" } There are other advanced features. You can remove the [FromBody] decorator on your input and let MVC binding map the properties: [HttpPost("/test/{rootId}/echo/{id}...

AspNetCore 2.2.0 - AspNetCoreModuleV2 Error

Answer : You just need to install this package below. After that you can use the AspNetCoreModuleV2 :) https://dotnet.microsoft.com/download/thank-you/dotnet-runtime-2.2.2-windows-hosting-bundle-installer When installing, please notice to install as administrator. As part of the installation the applicationHost.config file will be updated to include AspNetCoreModuleV2 and its dll. this is one of the reasons why it's important to run installation with admin privilege. I have the same issue. it is something wrong with AspNetCoreModuleV2 : modules="AspNetCoreModuleV2" The site is working when I change the modules to AspNetCoreModule in the web.config : modules="AspNetCoreModule"

Can I Use HttpClientFactory In A .NET.core App Which Is Not ASP.NET Core?

Answer : According to the documentation HttpClientFactory is a part of .Net Core 2.1, so you don't need ASP.NET to use it. And there some ways to use are described. The easiest way would be to use Microsoft.Extensions.DependencyInjection with AddHttpClient extension method. static void Main(string[] args) { var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider(); var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>(); var client = httpClientFactory.CreateClient(); } Thanks for replies. So it is possible to use in console app. There are a few ways to do this, depending on what way you want to go. Here are 2: Directly add to ServiceCollection e.g. services.AddHttpClient() Use Generic host e.g. Add httpclientFactory in .ConfigureServices() method See here for blog post using in console app As one of the answers suggests, you do not need ASP.NET to use it However, you need a bit of work to ge...

"415 Unsupported Media Type" For Content-Type "application/csp-report" In ASP.NET Core

Answer : The following example shows how to add support to the SystemTextJsonInputFormatter for handling additional media-types: services.AddControllers(options => { var jsonInputFormatter = options.InputFormatters .OfType<SystemTextJsonInputFormatter>() .Single(); jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report"); }); This is a two-step process: Interrogate the configured list of input-formatters to find the SystemTextJsonInputFormatter . Add application/csp-report to its existing list of supported media-types ( application/json , text/json , and application/*+json ). If you're using Json.NET instead of System.Text.Json , the approach is similar : services.AddControllers(options => { var jsonInputFormatter = options.InputFormatters .OfType<NewtonsoftJsonInputFormatter>() .First(); jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report"); }) T...

Cannot Find Command 'dotnet Ef'?

Image
Answer : In my case, the tools folder didn't exist inside %USERPROFILE%\.dotnet\ so I had to run the command dotnet tool install --global dotnet-ef to install dotnet ef. Then I was able to run dotnet ef... This was the result of the above install command: Note to readers: If you haven't installed dotnet ef , you need to install it first: dotnet tool install --global dotnet-ef . The question-asker already did that. You need to do that first before the rest of this answer can help. How to fix this For Linux and macOS , add a line to your shell's configuration: bash / zsh : export PATH="$PATH:$HOME/.dotnet/tools/" csh / tcsh : set path = ($path $HOME/.dotnet/tools/) When you start a new shell/terminal (or the next time you log in) dotnet ef should work. For Windows : See this question on how to add to the PATH environment variable. You need to add %USERPROFILE%\.dotnet\tools to the PATH . What's going on? The .NET Core 3.0 (preview) ...

Alternative Solution To HostingEnvironment.QueueBackgroundWorkItem In .NET Core

Answer : Update December 2019: ASP.NET Core 3.0 supports an easy way to implement background tasks using Microsoft.NET.Sdk.Worker. It's excellent and works really well. As @axelheer mentioned IHostedService is the way to go in .NET Core 2.0 and above. I needed a lightweight like for like ASP.NET Core replacement for HostingEnvironment.QueueBackgroundWorkItem, so I wrote DalSoft.Hosting.BackgroundQueue which uses.NET Core's 2.0 IHostedService. PM> Install-Package DalSoft.Hosting.BackgroundQueue In your ASP.NET Core Startup.cs: public void ConfigureServices(IServiceCollection services) { services.AddBackgroundQueue(onException:exception => { }); } To queue a background Task just add BackgroundQueue to your controller's constructor and call Enqueue . public EmailController(BackgroundQueue backgroundQueue) { _backgroundQueue = backgroundQueue; } [HttpPost, Route("/")] public IActionResult SendEmail([FromBody]emailRequest) { ...

Can Not Connect To Sql Server From Docker Supported Asp.net Core Project

Answer : This took me some time to work out, there are a number of small issues that may be wrong, which makes it frustrating. This can get even more frustrating as the .net core web application visual studio 2017 project that gets auto-generated doesn't work straight out of the box. Having this experience as your first exposure to Docker isn't ideal. I initially also had the incorrect assumption that the docker image would come with SQL Server inside the container, this is not the case, it's trying to access the database server that must be pre-installed on the host machine. Steps to follow (tested for a windows docker image, rather than linux); 1) Get the IP address of your host machine, by running a command prompt and typing IPCONFIG 2) Set the database connection string within you appsettings.json file to this Ip address, followed by the SQL Server port number, i.e.; 192.168.X.X,1433 3) Set the connection string not to use Trusted_Connection (delete thi...

ASP.NET Core Testing - Get NullReferenceException When Initializing InMemory SQLite Dbcontext In Fixture

Answer : I encountered this problem while trying to do EF Core scaffolding for an Sqlite database. The problem was that I had installed Microsoft.EntityFrameworkCore.Sqlite.Core rather than Microsoft.EntityFrameworkCore.Sqlite . I uninstalled the former package, and ran this command: Install-Package Microsoft.EntityFrameworkCore.Sqlite -Version 3.1.2 Then everything worked. Yup... My bad. I had installed Microsoft.Data.Sqlite.Core version 3.0.0 when I needed version 2.2.6 and I had not installed Microsoft.Data.Sqlite 2.2.6, which I have since installed. It's working now. Also, FYI: both .UseSqlite("Data Source=:memory:") and .UseSqlite("DataSource=:memory:") work. I had similar issue when trying to open Microsoft.Data.Sqlite.SqliteConnection , it was throwing System.NullReferenceException as well. The class which was initializing the connection was in library project referencing: Microsoft.Data.Sqlite - v3.1.2 Microsoft.Data.Sqlite.Core - v3...

Calling 'BuildServiceProvider' From Application Code Results In Copy Of Singleton Warning. How Do I Avoid This?

Image
Answer : If called BuildServiceProvider() in ConfigureServices, shown warning "Calling 'BuildServiceProvider' from application code results in a additional copy of Singleton services being created" I solved this issue: Create another function (which passed argument is IServiceCollection) and into the function call BuildServiceProvider() For example your code it should be: public void ConfigureServices(IServiceCollection services) { if (HostingEnvironment.EnvironmentName == "Local") { services.AddHealthChecksUI() .AddHealthChecks() .AddCheck<TestWebApiControllerHealthCheck>("HomePageHealthCheck") .AddCheck<DatabaseHealthCheck>("DatabaseHealthCheck"); } services.Configure<PwdrsSettings>(Configuration.GetSection("MySettings")); services.AddDbContext<PwdrsContext>(o => o.UseSqlServer(Configuration.GetConnectionString("PwdrsConnectionRoot...