kros-sk / kros.aspnetcore Goto Github PK
View Code? Open in Web Editor NEWThis repo contains utilities helping for building modern cloud-based web applications on Windows, Mac, or Linux.
License: MIT License
This repo contains utilities helping for building modern cloud-based web applications on Windows, Mac, or Linux.
License: MIT License
It would be nice to add exceptions transformation to http reponse statuses in ProblemDetailsExtensions in Kros.ProblemDetails.Extensions project, which is already defined in ErrorHandlingMiddleware
Then, we can avoid using both middlewares. It will be enough to use only ProblemDetail middleware.
It would be nice to allow add multiple request assemblies when configuring pipeline behavior for mediatR.
If command are in multiple asssemblies, it looks like:
.AddPipelineBehaviorsForRequest<ICompanySubResourceCommand>(config =>
{
config.RequestsAssembly = Assembly.GetEntryAssembly();
})
.AddPipelineBehaviorsForRequest<ICompanySubResourceCommand>(config =>
{
config.RequestsAssembly = typeof(CopyInvoiceCommand).Assembly;
})
Nicer version would be like
.AddPipelineBehaviorsForRequest<ICompanySubResourceCommand>(config =>
{
config.RequestsAssemblies.Add(Assembly.GetEntryAssembly());
config.RequestsAssemblies.Add(typeof(CopyInvoiceCommand).Assembly);
})
For using Azure app configuration need connection string to azure portal.
I need use similar code:
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options => {
options.Connect(settings["ConnectionStrings:AppConfig"])
.UseFeatureFlags();
});
})
.UseStartup<Startup>();
});
File appsettings.local.json is loading in startup, but I need access in Program.CreateHostBuilder.
Appsettings.json contains only
"ConnectionStrings": {
"AppConfig": ""
}
During loading CreateHostBuilder is throw exception System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')'
, because is empty in appsetting.json.
Move
config.AddJsonFile("appsettings.local.json", optional: true);
into Program.CreateHostBuilder.
as extension.
The problem is in calling UseSwaggerUI
. There are hardcoded values:
/v1/
in c.SwaggerEndpoint
string.Empty
in c.OAuthClientSecret
Both should be taken from swaggerDocumentationSettings
.
Method ClaimsPrincipalExtensions.GetUserId
returns int
user id, but we use long
ids.
Mentioned method return type should be long
.
Create extension to add Azure App Configuration configuration source to configuration builder.
Add:
By default in appsettings.json exists "AllowedHosts": "*"
After this settings app failed with error:
Object reference not set to an instance of an ojbect.
For sharing this code:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile($"appsettings.local.json", optional: true)
.AddEnvironmentVariables();
Create kros extensions for managing ProblemDetails in http response.
Add support for fluent validation problem details.
Logging new application insight property for route pattern.
Now is logging full url, with all ids (DELETE/Companies/789/BankAccounts/123).
New property should log pattern (DELETE/Companies/{CompanyId}/BankAccounts/{BankAccountId})
Link on SwaggerUI contain href="about:blank" attribute instead of href="someValidUrlFromAppSettings"
Open proper web address from appsetings
Open blank page
Start logging company id and user id into application insights.
Will be uses for monitoring and customer care.
services.ConfigureSwaggerGen(options => { options.CustomSchemaIds(x => x.FullName); // https://wegotcode.com/microsoft/swagger-fix-for-dotnetcore/ });
In some cases when using Kros.MassTransit.AzureServiceBus package to configure Azure Service Bus consumers in ASP.NET Core 3.0 app, application fails during startup with following error:
System.TypeLoadException: 'Method 'RegisterExecuteActivity' on type 'MassTransit.ExtensionsDependencyInjectionIntegration.Configuration.Registration.DependencyInjectionContainerRegistrar' from assembly 'MassTransit.ExtensionsDependencyInjectionIntegration, Version=5.5.6.0, Culture=neutral, PublicKeyToken=b8e0e9f2f1e657fa' tried to implicitly implement an interface method with weaker type parameter constraints.'
So far unknown. For some configuration it works, for some not.
Application should start without any errors and ASB should be working.
Application fails upon startup.
When using user assigned managed identity, client ID of this identity must be specified when connectiong to Azure App Configuration. We do not support this, so we can use only system assigned managed identities.
We do not want to have secret configuration values in appsettings.json
, not even if they are set there during deployment pipeline. We should load secrets directly from key vault as configuration values.
Adding key vault as configuration source must be simple as calling AddAzureKeyVault()
method in program start:
// Minimal API
builder.Configuration.AddAzureKeyVault();
// Program.cs
public static IHostBuilder CreateWebHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(configBuilder =>
{
configBuilder.AddAzureKeyVault();
});
By default configuration is loaded from KeyVault
section in appsettings.json
, but can be tewaked in delegate parameter of AddAzureKeyVault(options)
.
"KeyVault": {
"Name": "key-vault-name",
"Prefixes": [ "prefix1", "prefix2" ],
"IdentityClientId": "13cd1e37-1351-4d76-889a-9eae0fbd3c76",
"ReloadInterval": "00:05:00"
}
Name
: Key vault name. If set, key vault configuration source is added to configuration builder. Then secrets from that key vault are loaded into configuration. If the name is not set, nothing is done.Prefixes
: List of prefixes, which limits secrets which are loaded. If present, only secrets with these prefixes will be loaded. In no prefix is set, all secrets are loaded. Prefixes here are set without trailing dash (-
), but secret names must contain it. For example if prefix is lorem
, secrets which name starts with lorem-
are loaded.IdentityClientId
: GUID of the user assigned managed identity, which will be used to connect to key vault. If not set, system assigned identity will be used.ReloadInterval
: Timespan for polling key vault for changes. If not set, reloading will be disabled.Name of the key vault secret can not containt dot (.
), nor colon (:
), so double dash (--
) must be used for hierarchical configuration values. For example secret with name ConnectionStrings--DefaultConnection
will be used as configuration value for:
"ConnectionStrings": {
"DefaultConnection": ""
}
If some prefix is present, the name of the secret will be prefix-ConnectionStrings--DefaultConnection
.
Support for ServiceName in ApplicationInsights. Inspired by Titans...
Aktalne sa cache-uje podla jwt tokenu a path z requestu.
Ak to nie je v cache, tak sa vola autorizacna sluzba, ktora do claimov vlozi connection id.
Avsak ak sa connection id zmeni (uzivatel urobil refresh, alebo pouziva aplikaciu v 2 taboch),
tak v claimoch sa nezmeni connection id a nasledne sa preposialaju cez signalR spravy so zlym connection id.
Ak request obsahuje hlavicku connection id, tak do cache pridat zaznam aj s connection id/
Add any other context or screenshots about the feature request here.
Ignore tag (like [JsonIgnore]) or configure values which don't be checked
when not using mvc in my webservice ControllerBaseExtensions.SendCommand throws null reference exception because it fails to create resource link url
string url = actionName != null
? controller.Url.Link(actionName, ret) // this returns null
: string.Empty;
In application insights are many postman requests that cause false alarms.
Postman requests will not log into application insights.
Nowadays it is not possible to distinguish messages from multiple environments on single service bus. Also every developer needs own service bus for testing purposes.
Support definition of message prefix in application configuration, i.e appsettings.json
:
...
"AzureServiceBus": {
"ConnectionString": "",
"TokenTimeToLive": 60,
"MessagePrefix": "Staging", // <=== this
"Endpoints": {
...
Created topic address where services can subscribe will be:
{ServiceBusAdress}/{Prefix}-{Namespace/MessageName}
Prefix can be used to specify environment (dev, test, staging, ...) or also developer (Majo, Gabo...).
Both sides, publisher and subscriber, only need to set prefix in configuration and everything should work.
To be able to authorize a request from another API/Azure function as ‘grant_type: client_credentials’
Another API/ Azure function will request an access token from IS based on given credentials (client_id, client_secret, grant_type). This token will then allow the foreign API to make requests of our API, which will be authorized against IS.
We need to send a request from the azure function to the search service, where the user access token no longer exists (we do not want to hold it internally)
As ASP.NET Core 3.0 has been released a couple of weeks ago, it would be nice if this solution targeted also .NET Core 3.0. I propose multi-platform targeting, so ASP.NET Core 2.2 apps would be still supported.
Projects in need of targeting .NET Core 3.0:
Projects in need of package upgrade so they would support .NET Core 3.0:
Cannot forget about multi-targeting for test projects:
For security reason add AddAuthorization
method to AddWebApi
method in project Kros.AspNetCore
It would be nice to create BadRequestException
and catch it in ErrorHandlingMiddleware
.
During reading Azure app configuration
ConfigurationBuilderExtenstions.AddAzureAppConfiguration
is possible read also feature flags, using this code:
options
.Select("_", LabelFilter.Null)
.Select("_", hostingContext.HostingEnvironment.EnvironmentName)
.UseFeatureFlags();```
GatewayAuthorizationMiddleware now returns only 401 (Unauthorized) for all errors during getting JWTtoken. It would be helpfull to return also another errors (NotFound
, Forbidden
, ... ).
Application Insights readme is missing and project is not referenced from main readme file.
Add extension for adding health checks for identity server.
public static class HealthChecksBuilderExtensions
{
public static IHealthChecksBuilder AddIdentityServerHealthChecks(this IHealthChecksBuilder healthChecksBuilder, IConfiguration configuration)
{
var identityServerOptions = configuration.GetSection("IdentityServerHandlers").Get<IdentityServerOptions[]>().ToList();
foreach (var option in identityServerOptions)
{
healthChecksBuilder.AddUrlGroup(
new Uri(option.AuthorityUrl),
name: $" IdentityServer handler for scheme {option.AuthenticationScheme}",
tags: new string[] { "url" });
}
return healthChecksBuilder;
}
}
TelemetryProcessorChainBuilder has method UseAdaptiveSampling, but there is no way to set it.
I would like configure exluded types for loging.
Implement extension method for JsonPatchDocument<TModel>
for extracting sub items.
Add extensions for health checks:
Notes:
Report and writer
Tests
public static class UrisHealthCheckBuilderExtensions
{
///
/// Add a health check for single uri.
///
/// The .
/// The uri to check.
/// The health check name. Optional. If null the type name 'uri-group' will be used for the name.
///
/// The that should be reported when the health check fails. If null then
/// the default status of will be reported.
///
/// A list of tags that can be used to filter sets of health checks.
/// The proxy for http request. Optional
/// The .
public static IHealthChecksBuilder AddUrlGroup(this IHealthChecksBuilder builder, Uri uri, string name, Uri proxy,
HealthStatus? failureStatus = null, IEnumerable tags = null)
{
if (proxy == null)
{
builder.Services.AddHttpClient("HealthCheck");
}
else
{
builder.Services
.AddHttpClient("HealthCheck")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
Proxy = new WebProxy(proxy)
});
}var options = new UriHealthCheckOptions(); options.AddUri(uri); var registrationName = name; return builder.Add(new HealthCheckRegistration( registrationName, sp => CreateHealthCheck(sp, registrationName, options), failureStatus, tags)); } private static UriHealthCheck CreateHealthCheck(IServiceProvider sp, string name, UriHealthCheckOptions options) { var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>(); return new UriHealthCheck(options, () => httpClientFactory.CreateClient("HealthCheck")); } }
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.