Can't resolve `AddAuthorization` in my .NET 6 class library - c#

So I'm sure I'm missing something super obvious here, but I can't seem to pinpoint it.
I have a .NET 6 class lib:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
</ItemGroup>
</Project>
I have a builder in my lib that is trying to register the AddAuthorization service, but it will not resolve for some reason:
namespace MyLib;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
public class MyLibBuilder
{
public IServiceCollection Services { get; }
public MyLibBuilder(IServiceCollection services)
{
Services = services;
}
public MyLibBuilder MapAuthorizationPolicies()
{
Services.AddAuthorization();
return this;
}
}
I've:
triple checked that I have Microsoft.Extensions.DependencyInjection and Microsoft.AspNetCore.Authorization installed
Rebuilt the solution
Unloaded and reloaded the project
And no dice for any. I'm sure it'll click right away once i step away for a day, but it's really bothering me 🤣 What the heck am i missing?
Note: If I change it to a Microsoft.NET.Sdk.Web project, it will resolve, but then I need a Main to run which is moot here since this is just a class lib. Web has to be doing something else that I'm missing but i'm not seeing it...

According to this this was a breaking change.
The below was the recommended solution, though I did try referencing Policy still with no joy.
Either add a reference to Microsoft.AspNetCore.Authorization.Policy or use AddAuthorizationCore instead

Related

error CS0246: The type or namespace name 'ValuesController' could not be found (are you missing a using directive or an assembly reference?)

I'm working with .NET and getting this error, It's my first time doing this so I'm really not sure how to fix this. I have two files that I'm working with, one is called "UnitTest1.cs" which is where the error is occurring and it's saying it occurs on line 12 in regards to the 'ValuesController' and that code is right here
using System;
using Xunit;
using SimpleAPI.Controllers;
namespace SimpleAPI.Test
{
public class UnitTest1
{
ValuesController controller = new ValuesController();
[Fact]
public void GetReturnsMyName()
{
var returnValue = controller.Get(1);
Assert.Equal("Mitchell Privett", returnValue.Value);
}
[Fact]
public void Test1()
{
}
}
}
I'm not sure if this other file affects it or not, but it's in the same directory and it's called SimpleAPI.Test.csproj and the code for that is here:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SimpleAPI\SImpleAPI.csproj" />
</ItemGroup>
</Project>
The class ValuesController is not defined.
Include the according library with the using statement:
using MyLibraryThatContainsValuesController;
In your test project, add a project reference to your main project (SimpleAPI) if you haven't done already. If you're using Visual Studio Community, you can do so by right clicking on your test project file (SimpleAPI.Test) in the solution explorer -> Add -> Project Reference... -> mark the checkbox next to the SimpleAPI -> click OK
If the problem's still there, go back to your test project and add a using statement refering to the namespace of the ValuesController class. If you don't know the namespace, open your ValuesController class. On top of the code (after using statements) you'll see something like:
namespace SimpleAPI.Controllers
There's your namespace!

How to avoid certificate issues when setting a SQLite password?

I have C# application (targeting .NET Framework) and I try to set a password on my (completely new) SQLite database.
This is my code
using System;
using System.Data.SQLite;
namespace ConsoleApp10
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Begin");
var csWithoutPw = new SQLiteConnectionStringBuilder
{
DataSource = "C:\\Databases\\SQLiteWithEFPw.db",
Version = 3
}.ConnectionString;
SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(csWithoutPw);
conn.Open();
conn.ChangePassword("Kabouter");
conn.Close();
Console.WriteLine("End");
}
}
}
This is my csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net462</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SQLite" Version="3.13.0" />
<PackageReference Include="Stub.System.Data.SQLite.SEE" Version="1.0.115.6" />
<PackageReference Include="System.Data.SQLite" Version="1.0.115.5" />
<PackageReference Include="System.Data.SQLite.Linq" Version="1.0.115.5" />
</ItemGroup>
</Project>
Unfortunately, my code crashes when connecting with a NotSupportedException referring to some certificate issue I do not understand.
'{cannot find a suitable package certificate file for plugin in
"C:\Users\dacohen\source\repos\ConsoleApp10\ConsoleApp10\bin\Debug\net462\SDS-SEE.exml"
: "invalid file name"} {}'
How can I avoid this problem? I just want to set the password..... I found code online but for .NET Framwork 4.6.2 it does not seem to work or so.
In addition, this is why I set my password before opening.

Error when adding identity migrations in asp.net core

When I run
dotnet ef migrations add IdentityInitial -p Data -s SignalRreactjs -c IdentityAppDbContext -o Identity/Migrations
I get this response back
An error occurred while accessing the Microsoft.Extensions.Hosting
services. Continuing without the application service provider. Error:
Some services are not able to be constructed (E rror while validating
the service descriptor 'ServiceType:
Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime: Scoped
ImplementationType: Microsoft.AspNetCore.Identity.Secu
rityStampValidator1[Data.Models.AppUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Authentication.ISystemClock' while attempting to activate 'Microsoft.AspNetCore.Ide ntity.SecurityStampValidator1[Data.Models.AppUser]'.) (Error while
validating the service descriptor 'ServiceType:
Microsoft.AspNetCore.Identity.ITwoFactorSecurityStampValidator Lifet
ime: Scoped ImplementationType:
Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator1[Data.Models.AppUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Authenti cation.ISystemClock' while attempting to activate 'Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator1[Data.Models.AppUser]'.)
Unable to create an object of type 'IdentityAppDbContext'. For the
different patterns supported at design time, see
https://go.microsoft.com/fwlink/?linkid=851728
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<IdentityAppDbContext>(x =>
{
x.UseSqlServer(_config.GetConnectionString("IdentityConnection"));
});
services.AddIdentityCore<AppUser>().AddEntityFrameworkStores<IdentityAppDbContext>()
.AddSignInManager<SignInManager<AppUser>>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "SignalRreactjs", Version = "v1"});
});
}
IdentityAppDbContext.cs
using Data.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Data.Identity
{
public class IdentityAppDbContext : IdentityDbContext<AppUser>
{
public IdentityAppDbContext(DbContextOptions<IdentityAppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
}
AppUser.cs
using Microsoft.AspNetCore.Identity;
namespace Data.Models
{
public class AppUser : IdentityUser
{
public string DisplayName { get; set; }
public string ImageUrl { get; set; }
}
}
Data.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.4" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.8.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
</ItemGroup>
</Project>
SignalRreactjs.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0-preview.2.21154.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="Controllers" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Data\Data.csproj" />
</ItemGroup>
</Project>
The problem is that you're using AddIdentityCore(), which (unlike AddIdentity() or AddDefaultIdentity(), all of which are confusing btw) doesn't contain a call to AddAuthentication(). Since ISystemClock is added by AddAuthentication().
So you need to add a call yourself, preferably below AddIdentityCore():
services.AddAuthentication();
Possibly you'll also need to provide your authentication configuration, depending on your authentication requirements.
Alternatively, you can replace AddIdentityCore() with AddIdentity() or AddDefaultIdentity(). That way the problem won't occur, and you'll have authentication configured with Identity. But that configuration includes possibly annoying cookies and redirection, and it's generally only good when you're working on an MVC project (i.e. not web API).
You can try registering ISystemClock in your ConfigureServices method in the startup class.
services.TryAddSingleton<ISystemClock, SystemClock>();
But it is not recommended. Similar StackOverflow Question

Visual Studio Code : Debugging unit tests works with net50 target framework but not with net48

I'm setting a test environment for a .net library using VS Code. I tried different configurations and after reading this article, I came up with this solution :
Project file :
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<IsPackable>false</IsPackable>
<GenerateProgramFile>false</GenerateProgramFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="nunit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
</ItemGroup>
</Project>
Program.cs
using System;
using DebugTest.App;
using DebugTest.Test;
namespace DebugTest
{
class Program
{
static void Main(string[] args)
{
UnitTests test = new UnitTests();
test.Setup();
test.TestAdd();
}
}
}
Pseudo lib
using System;
namespace DebugTest.App
{
public static class Calculator
{
public static double Add(double x, double y)
{
return x + y;
}
}
}
UnitTest.cs
using System;
using DebugTest.App;
using NUnit.Framework;
namespace DebugTest.Test
{
public class UnitTests
{
[SetUp]
public void Setup()
{
}
[Test]
public void TestAdd()
{
double x = 2d;
double y = 2d;
Assert.AreEqual(9999d, Calculator.Add(x, y));
}
}
}
With this configuration all works fine. I can :
dotnet build
dotnet test : starts the tests in terminal
launch with appropriate configuration in launch.json : If I set breakpoints, I can debug tests through main method
click on "Debug All Tests" or "Debug Test" lens in VSCode to debug tests.
Things got complicated when I tried to change the target framework from net5.0 to net48. I had to change my csproj this way :
New csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<IsPackable>false</IsPackable>
<OutputType>exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="nunit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
</ItemGroup>
</Project>
What still works :
dotnet build
dotnet test
What doesn't work anymore :
launch (I didn't forget to change the program path) : The program main is launched as I can see the exception for the failed test. In addition there are other warnings (The target process exited without raising CoreCLR...). If I set breakpoints in Program.cs or UnitTest.cs, they are not hit anymore
click on "Debug All Tests" or "Debug Test" lens : Raises an error in VSCode : Failed to start debugger with a stacktrace mentionning OmniSharp.
I tried many things (cleaning bin and obj folders, etc) and read many forums threads with similar problems but none of them were related to net48.
So, my question is : How can I achieve test debugging in a net48 project in VSCode ?

Azure Function (using DI) cannot remove "/api" route prefix

So I'm aware of these two questions that seem to be asking the same thing:
How to remove the word ‘api’ from Azure functions url
How to change the base "/api" path on Azure Functions (v2)?
However, I can still not get rid of the "api" prefix in my route.
My host.json looks like:
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": ""
}
}
}
And on my HttpTrigger I'm setting my custom route:
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "myapp")] HttpRequest request,
However, when I run the app locally the end point is coming up as:
[POST] http://localhost:7071/api/myapp
If I change my host.json to:
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": "something"
}
}
}
My app is now running on:
[POST] http://localhost:7071/something/myapp
So it appears that giving an empty string "" is just not working. Any ideas? (I've done all the usual stuff: clean solution, delete bin/obj folder etc.)
FYI from my function app I'm using:
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.7" />
EDIT:
I'm also referencing these packages from the function app (though I don't see how this would cause this problem):
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.1" />
EDIT 2
I've narrowed down the problem to this code that is called in Startup.cs:
IConfiguration configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
IConfiguration combinedConfig = new ConfigurationBuilder()
.AddConfiguration(configuration)
.AddAzureKeyVault(kvEndpoint, kvClient, new DefaultKeyVaultSecretManager());
.Build();
builder.Services.AddSingleton(combinedConfig);
// <-- this line causes the prefix "" to revert to "/api"
It essentially is adding key vault as a configuration provider to the stack of providers all ready there. (Note it doesnt matter what .Add methods I call on configuration builder, its the registration that is causing a problem). Is there another way to write this maybe?
So the mistake I seem to have made was very small. In the following code:
IConfiguration configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
IConfiguration combinedConfig = new ConfigurationBuilder()
.AddConfiguration(configuration)
.AddAzureKeyVault(kvEndpoint, kvClient, new DefaultKeyVaultSecretManager());
.Build();
builder.Services.AddSingleton(combinedConfig);
ConfigurationBuild.Build() actually returns a IConfigurationRoot, NOT a IConfiguration (IConfigurationRoot is a superset of IConfiguration). So when registering it I was loosing something (probably config provider information).
Simply changing:
IConfiguration combinedConfig
to
IConfigurationRoot combinedConfig
fixes the problem (or you can use var, which I probably should have!).
Though this fixes the problem I am still a little confused why before changing the routePrefix in host.json to some non-empty string works but setting it to empty string does not. Would have thought simply having the setting in the host.json at all would just apply the value and not having it there would mean reverting to the default "api".
I tried, and it's working!
I used VS2019, Created Azure function default project with HTTP trigger and remove route prefix from host.json
Proj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.31" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
After updating nuget packages with latest version, it's working.
Proj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.Azure.WebJobs.Core" Version="3.0.16" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.2" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.7" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>

Categories