#StackBounty: #c# #asp.net-core #signalr #blazor-server-side Clients.User().SendAsync() Not Communication With hubconnection.on

Bounty: 200

Here I have blazor server app in which I have signalR hub called SessionChatHub, and it contains method AssignmentCreatedNotification(HashSet<string> userIdList, string name) which receives userIdList (userIdList is identity id accessed from database AspNetUsers table) and name as parameter and send the name to all the userid of userIdList parameter.

Now the problem is that even after getting values in userIdList and name parameter hubConnection.On<string>("ReceiveAssignmentCreatedNotification", NotifyStudentAboutAssignmentCreated); is not fired that is NotifyStudentAboutAssignmentCreated(string name) is not called.

But when there is Clients.All.SendAsync("ReceiveAssignmentCreatedNotification", name); NotifyStudentAboutAssignmentCreated(string name) method is called,but it is not calling on await Clients.User(userId).SendAsync("ReceiveAssignmentCreatedNotification", name);

userIdList: (userIdList is identity id accessed from database AspNetUsers table)

Below is Hub

public class SessionChatHub:Hub
{            
    public async Task AssignmentCreatedNotification(HashSet<string> userIdList, string name)
    {
        foreach (var userId in userIdList)
        {
            await Clients.User(userId).SendAsync("ReceiveAssignmentCreatedNotification", name);
        }
    }
    public async override Task OnConnectedAsync()
    {
        Console.WriteLine($"{Context.ConnectionId} connected");
      
    }
    public override async Task OnDisconnectedAsync(Exception e)
    {
        Console.WriteLine($"Disconnected {e?.Message} {Context.ConnectionId}");
        await base.OnDisconnectedAsync(e);
    }
}

Below is my oninitialized where we receive signalr hub

protected async override void OnInitialized()
    {
        var container = new CookieContainer();
        var cookie = new Cookie()
        {
            Name = ".AspNetCore.Identity.Application",
            Domain = "localhost",
            Value = CookiesProvider.Cookie
        };

        container.Add(cookie);


        hubConnection = new HubConnectionBuilder()
      .WithUrl(NavigationManager.ToAbsoluteUri("/sessionchathub"), options =>
      {
          options.Cookies = container;
      }).Build();
        hubConnection.ServerTimeout = TimeSpan.FromMinutes(60);


        hubConnection.On<string>("ReceiveAssignmentCreatedNotification", NotifyStudentAboutAssignmentCreated);

        await hubConnection.StartAsync();
    }

Method to be call

    public void NotifyStudentAboutAssignmentCreated(string name) // This method is not called from oninitialized  hubConnection.On<string>("ReceiveAssignmentCreatedNotification", NotifyStudentAboutAssignmentCreated);
    {
        NotificationHandler.AssignmentNotificationCount = 1;
        StateHasChanged();
    } 

I also have OnAfterRenderAsync

 protected async override Task OnAfterRenderAsync(bool firstRender)
 {
    

    //if (firstRender)
    //{
    await jSRuntime.InvokeVoidAsync("AddSelect2ForClassIdInCreateEditTeacherAssignment");
    await jSRuntime.InvokeVoidAsync("AddSelect2ForSubjectIdInCreateEditTeacherAssignment");
    await jSRuntime.InvokeVoidAsync("AddSelect2ForChapterIdInCreateEditTeacherAssignment");
    //}
    await base.OnAfterRenderAsync(firstRender);
 }


Get this bounty!!!

#StackBounty: #asp.net-core #security #csrf Why is aspnet preventing browser page caching when a csrf token is present?

Bounty: 50

As documented here, generating a csrf token with asp.net will also prevent the response to be cached by the browser.

Generates an AntiforgeryTokenSet for this request and stores the cookie token in the response. This operation also sets the "Cache-control" and "Pragma" headers to "no-cache" and the "X-Frame-Options" header to "SAMEORIGIN".

I initially assumed that this decision was made to prevent users from submitting a "stale" request token by using the browser "back" button. I later noticed that this might not be the reason, since :

  • asp.net keeps the same cookie token for the whole session.
  • asp.net allows the same request token to be submitted many times as long as the cookie token doesn’t change.

So, from my current understanding, using the browser back button and submit a cached html page should not be a problem ?

What is then the justification for disabling browser page caching when it contains a csrf token ? Is this a security best practice ?

EDIT

As @serpent5 rightfully pointed out, the header Cache-Control: no-store ensures that a public cache won’t cache the response and serve it to a different user. To clarify, I am more specifically interested in knowing if enabling browser caching (Cache-Control: private) would have a negative impact on security.


Get this bounty!!!

#StackBounty: #c# #entity-framework #asp.net-core #kubernetes #entity-framework-core Entity Framework Core leaving many connections in …

Bounty: 100

I have a .net core API using Entity Framework Core. The DB context is registered in startup.cs like this:

  services.AddDbContext<AppDBContext>(options =>
         options.UseSqlServer(connectionString,
         providerOptions => providerOptions.CommandTimeout(60))); 

In connection string I set

  Pooling=true;Max Pool Size=100;Connection Timeout=300

The controller calls methods in a service which in turn makes calls to aysnc methods in a repo for data retrieval and processing.

All worked well if concurrent user is under 500 during load testing. However beyond that number I start to see a lot of timeout expired errors. When I checked the database, there’s no deadlock but I could see well over 100 connections in sleeping mode(the API is hosted on two kubernetes pods). I monitored these connections during the testing and it appeared that instead of current sleeping connections being reused, new ones were added to the pool. My understanding is entity framework core manages opening and closing connections but this didn’t seem to be the case. Or am I missing anything?

The error looks like this:

StatusCode":500,"Message":"Error:Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. Stack Trace: at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)n at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)n at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)n at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)n at Microsoft.Data.SqlClient.SqlConnection.Open()n at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)n at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)n at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction(IsolationLevel isolationLevel)n…………………

An example of how the dbcontext was used:

the controller calls a method in a service class:

  var result = await _myservice.SaveUserStatusAsync(userId, status);

then in ‘myservice’:

  var user = await _userRepo.GetUserAsync(userId);

  ....set user status to new value and then

  return await _userRepo.UpdateUserAsync(user);

then in ‘userrepo’:

  _context.user.Update(user);
   var updated = await _context.SaveChangesAsync();
   return updated > 0;


Get this bounty!!!

#StackBounty: #angular #amazon-web-services #asp.net-core #aws-lambda #angular5 Error Code: 0 ExceptionMessage: Http failure response f…

Bounty: 50

I am getting this error "Error Code: 0 ExceptionMessage: Http failure response for (unknown URL): 0 Unknown Error" on my Angular 5 project.

However, I am not able to recreate this issue, I saw this repeated issue on the Rollbar error log. I tried the same steps on my local machine, also tried to recreate in different browsers like chrome, safari, etc but no luck.

I’m using AWS lambda with .NET core 2.1, API proxy gateway, and Angular 5 on FrontEnd.

AngularJs code

getOrgPublicAssetName(id: number): Observable<any> {
    let content = this.appSharedService.getSitecontents();
    if (content !== '')
      return Observable.of(content);
    if (id !== undefined)
      return <Observable<any>>(
        this.httpClient
          .get(this.organizationUrl + '/SiteContent/' + id)
          .map(result => {
            this.appSharedService.setsitecontents(result);
            return result;
          })
          .pipe(catchError(this.exceptionService.catchBadResponse))
      );
    else return Observable.of();
  }

Following is my startup.cs configure function where I am already using cors.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseXRay("Organizations");
            app.UseMiddleware(typeof(ErrorHandlingMiddleware));

            Environment.SetEnvironmentVariable(EnvironmentVariableAWSRegion.ENVIRONMENT_VARIABLE_REGION, Configuration["AWS:Region"]);

            // Create a logging provider based on the configuration information passed through the appsettings.json
            // You can even provide your custom formatting.
            loggerFactory.AddLambdaLogger(Configuration.GetLambdaLoggerOptions());

            //Enable swagger endpoint if the environment is not production

            if (!IsProductionEnvironment)
            {
                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger();

                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    if (env.EnvironmentName == "Local")
                        c.SwaggerEndpoint(SwaggerLocalEndpoint, ApiName);
                    else
                        c.SwaggerEndpoint(SwaggerEndpoint, ApiName);
                });
            }

            app.UseCors(policy =>
            {
                //TODO: This has to be addressed once we deploy both api and ui under the same domain
                policy.AllowAnyOrigin();
                policy.AllowAnyHeader();
                policy.AllowAnyMethod();
                policy.WithExposedHeaders("WWW-Authenticate");
                policy.WithExposedHeaders("X-Total-Count");
            });
            app.UseAuthentication();
            app.UseMvc(routeBuilder =>
            {
                routeBuilder.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
                routeBuilder.MapODataServiceRoute("odata", "odata", OrganizationModelBuilder.GetEdmModel());
            });
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            app.UseResponseCaching();
        }
    }


Get this bounty!!!

#StackBounty: #angular #asp.net-core #jwt Jwt and ASP.NET CORE Authorization AspNetRoleClaims

Bounty: 50

How to implement Jwt token with ASP.NET CORE Authorization AspNetRoleClaims and Angular?

I have the following default roles (user types) for exemple:

Admin (Gerencia)
User
Client

A user that has the claim to viewRoles can add its own roles with custom claims.

For example
worker
claims canViewClients canViewInventory….

A user that has a claim to view employees and edit them can select from a dropdown the user type has you can see on my image.
DropDown with user types

When the user selects a user type my application auto fills the claims the user can have access to by default. However the user can always uncheck or check different claims the auto fill is only there to save some time. Here is what my checkbox look like visually.

Claims

Each checkbox represents a claim.

To recap

  • The user types are not used to authorize endpoints only to visualy quickly populate the checkboxes.
  • Each checkbox represent a claim.

How can I Add claims/policies to my jwt cookie

Here are the important parts of my startup.cs file.

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.Configure<ApplicationSettings>(Configuration.GetSection("AppSettings")); 

        services.AddTransient<DatabaseMigrator>();
        services.AddDbContext<erp_colombiaDbContext>(options => options.UseMySql(
                 Configuration.GetConnectionString("DefaultConnection"),
                 optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(DesignTimeDbContextFactory).Assembly.FullName)));
        services.TryAddScoped<UserManager<Employee>>();
        services.TryAddScoped<SignInManager<Employee>>();

        services.AddIdentityCore<Employee>(options => 
            options.SignIn.RequireConfirmedAccount = false
        ).AddEntityFrameworkStores<erp_colombiaDbContext>();

        //Jwt Authentication
        var key = Encoding.UTF8.GetBytes("myKey");

        services.Configure<IdentityOptions>(options =>
        {
            options.Password.RequireDigit = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireLowercase = false;
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 4;
        });

        services.AddCors();

        //Jwt Authentication

        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;                
        }).AddJwtBearer(x =>
        {
            x.IncludeErrorDetails = true;
            x.RequireHttpsMetadata = false;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                RequireSignedTokens = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero
            };
            x.Events = new JwtBearerEvents
            {
                OnAuthenticationFailed = c =>
                {
                    // break point here
                    return Task.CompletedTask;
                },
            };
        });

        services.AddAuthorization(options =>
        {
        options.AddPolicy("ViewClientsPolicy",
            policy => policy.RequireClaim("View Clients"));
        });


        //services.AddControllersWithViews();
        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        services.AddMvc();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddScoped<IMenuService, MenuService>();
        services.AddScoped<IEmployeeService, EmployeeService>();
        services.AddScoped<IGeneralConfigurationService, GeneralConfigurationService>();
        services.AddScoped<IComponentLocationService, ComponentLocationService>();
        services.AddScoped<INewsService, NewsService>();
        services.AddScoped<INewsCategoryService, NewsCategoryService>();
        services.AddScoped<INewsCategoriesService, NewsCategoriesService>();
        services.AddScoped<IExternalLinksService, ExternalLinksService>();
        services.AddScoped<IClientService, ClientService>();
        services.AddScoped<ISupplierService, SupplierService>();
        services.AddScoped<IContactService, ContactService>();
        services.AddScoped<IUserTypeService, UserTypeService>();
        services.AddScoped<IComponentService, ComponentService>();
        services.AddScoped<IFamilyService, FamilyService>();

        services.AddScoped<IContractMenuService, ContractMenuService>();
        services.AddScoped<IContractService, ContractService>();

        services.AddScoped<IHolidayService, HolidayService>();
        services.AddScoped<IExpeditionService, ExpeditionService>();

        services.AddScoped<IKanbanService, KanbanService>();

    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseRouting();

        // global cors policy
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());


        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });


        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
}

Here is what my employee looks like

public class Employee : IdentityUser
{
    [Display(Name = "empName", ResourceType = typeof(SharedResource))]
    [Column("nombre")]
    public string Name { get; set; }

    [Display(Name = "empLastName", ResourceType = typeof(SharedResource))]
    [Column("apellido")]
    public string FamilyName { get; set; }

    [Display(Name = "empEmail", ResourceType = typeof(SharedResource))]
    [Column("correo")]
    public override string Email { get; set; }

   //And many more fields

}

In my angular app I have the following code to guard my enpoints. I am not sure how to modifie it so it requires claims?

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    if (localStorage.getItem('token') != null)
      return true;
    else {
      this.router.navigate(['/user/login']);
      return false;
    }
  }
}

Too login In my app I have the following code.

[HttpPost, Route("login")]
public async Task<IActionResult> Login([FromBody] LoginModel user)
{
    string passowrdHashed = HashPassword(user.Password);

    var userFromDb = await _userManager.FindByNameAsync(user.UserName);
    if (userFromDb == null) 
    {
        return Unauthorized();
    }
    else if (user != null && userFromDb.UserName==user.UserName
        && userFromDb.PasswordHash == passowrdHashed)
    {
        if (userFromDb.PasswordHash == HashPassword(_employeeService.DEFAULT_PASSWORD))
        {                    
            return Ok("Please change password!"); 
        }
        else
        {
           //*********************************************************************  
           //******      How to add Code to add claims???????????????      *******
           //*********************************************************************
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                new Claim("UserID", "1")
            }),
                Issuer = "jcortenbach",
                Expires = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superlongKeyWithALotOfWordsToMakeItMoreSecureWichIsGoodThankYouForReadingMySecretKey@45")), SecurityAlgorithms.HmacSha256Signature)
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            var token = tokenHandler.WriteToken(securityToken);
            return Ok(new { token });
        }
    }
    else 
    {
        return Unauthorized();
    }
}

Finaly when it comes to my bankend I think it should look something like this. For exemple the get client list code.

[Route("api/[controller]")]
[ApiController]
public class ClientsController : ControllerBase
{
    private readonly ILogger<ClientsController> _logger;
    private readonly IClientService _clientService;

    public ClientsController(erp_colombiaDbContext context, ILogger<ClientsController> logger, IClientService clientService)
    {
        _logger = logger;
        _clientService = clientService;
    }

// GET api/clients
[HttpGet]
[Authorize(Policy = "ViewClientsPolicy")]
public async Task<IEnumerable<ClientViewModel>> GetAsync()
{
    ClientViewModel clientViewModel;
    List<ClientViewModel> listClientViewModels = new List<ClientViewModel>();

    var clients = await _clientService.GetAllClients();

    foreach (var client in clients) 
    {
        clientViewModel = new ClientViewModel();
        clientViewModel.ClientId = client.ClientId;
        clientViewModel.Active = client.Active;
        clientViewModel.Address = client.Address;
        clientViewModel.City = client.City;
        clientViewModel.ClienteName = client.ClienteName;
        clientViewModel.ComercialEmployeeId = client.ComercialEmployeeId;
        clientViewModel.Confirmed = client.Confirmed;
        clientViewModel.CountryId = client.CountryId;
        clientViewModel.CreationDate = client.CreationDate;
        clientViewModel.DANE = client.DANE;
        clientViewModel.Department = client.Department;
        clientViewModel.ElectronicBillingEmail = client.ElectronicBillingEmail;
        clientViewModel.Eliminated = client.Eliminated;
        clientViewModel.NIT = client.NIT;
        clientViewModel.PostalCode = client.PostalCode;
        clientViewModel.Phone = client.Phone;

        listClientViewModels.Add(clientViewModel);
    }

    return listClientViewModels;
}

I am uncertain what to do next has there are many puzel pieces. Your help is greatly appreciated.

Recap of Questions

  1. How to add asp.net core roles to claims/polcies?
  2. How to connect claims/polcies to user?
  3. What to add in startup?
  4. How to add claims/polcies to jwt cookies?
  5. How to uses jwt claims/polices cookies in angular?

If you need more information I will gladly add it to my question.


Get this bounty!!!

#StackBounty: #c# #visual-studio #asp.net-core #asp.net-identity #razor-pages "Invalid login" when logging into my new Razor …

Bounty: 200

I created a new Razor Pages app. I ran that app and created an account. (A confirmation email was sent, which I clicked.) And that account was working. But today, I’m unable to log in.

Invalid login attempt.

Even though I believe I remember the password, I tried the Forgot Password feature. No email was sent.

I’ve reviewed my account in the database. Here are the values of the relevant columns from the AspNetUsers table:

  • EmailConfirmed: True
  • LockoutEnd: NULL
  • AccessFailedCount: 0

Next, I tried to scaffold the Login and Forgot Password so I could debug the code. But this failed. (You can see my post about this issue on GitHub.)

So at this point, I’m blocked. Can anyone else suggest other things I might try to resolve this issue? What other things can cause this behavior?


Get this bounty!!!

#StackBounty: #c# #html #asp.net-core #blazor Scroll click not working with NavigationManager.NavigateTo, and I can't use href beca…

Bounty: 100

I have a Blazor Server web app; .NET 5.

I am running into frustrations related to navigating between pages in my web app:

  • When I use NavigationManager.NavigateTo(uri, true), I am unable to open links using my scroll click (which would open the link in a new browser tab if I were to use href="uri" instead). It opens a new tab, but loads the same page I was already on.
  • When I use href="uri" instead, the scroll-click works. However, it introduces a new problem: with a ‘normal’ left-click, the new page loads but retains the scroll position of the previous page in a mobile browser (I have tested with mobile Safari, as well as the mobile emulator in Chrome).

I need to be able to scroll-click into a new tab, as well as have a new page load without retaining the previous page’s scroll position. Any tips?


Get this bounty!!!

#StackBounty: #c# #asp.net-core #iis #asp.net-core-3.0 Get the local path of a file in a virtual directory

Bounty: 50

I have an ASP.NET Core 3.0 MVC application with images in it. E.g.,

http://foo.bar/images/image.jpg

Now, the folder images is a virtual directory which is mapped to a network drive, such as \192.168.1.1images.

Question:

What method turns the information /images/image.jpg into \192.168.1.1imagesimage.jpg? I need to retrieve the physical path of the file from the relative web path.

In ASP.NET Web Forms, this could be done by something like Server.MapPath("~/images/image.jpg"), but this method doesn’t exist in ASP.NET Core’s HttpContext anymore.


Get this bounty!!!

#StackBounty: #c++ #asp.net-core #dependency-injection #coreclr Asp Net Core Dependency Injection doesn't work, if it started from …

Bounty: 100

First i try to explain the story.

I wanted to extend an C++/MFC application with REST-APIs, and decided to use for this purpose Asp .Net Core 5 in a library by bridging it to unmanaged code with C++/CLI library. (having a separete ASP application is doubled expenditure, and needed to be rewritten all the logic in C#. in that regard RESTful-Server should be in same process implemented)

Asp-Host is started in that way; C++/MFC -> C++/CLI -> ASP-Library (ASP referenced in CLI, CLI referenced in Native)

First problem was; Microsoft.Extensions.Hosting.Abstractions-Assembly could not be resolved. .runtimeconfig.json hat wrong framework reference. After every build it has to be manually with AspNetCore instead of NETCore corrected. (Done in PostBuildEvent)

Next problem; during the asp host build, asp could not resolve my ASP.dll assembly. This problem solved by OnAssemblyResolve event. I’m not sure whether it is correct solution. And AppDomain.BaseDirectory is an empty string, maybe it is the because of it, that my ASP-library could not found.

Finally could start the server, and it works. Then needed to use dependency injection, and my service could not be resolved from the controller. Then i used my ASP-library in another C#-project to test and it works. i’m sure that it doesn’t work if the entry point of process is unmanaged.

public interface IServerImpl
{
  void OnFail(String msg);
}

public class CServerImpl : IServerImpl
{
  public void OnFail(String msg)
  {
  }
}

… in Startup

public void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<IServerImpl, CServerImpl>();

  services.AddControllers();
}

… Controller

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
  private readonly ILogger<WeatherForecastController> _logger;
  private readonly IServerImpl _serverImpl;

  public WeatherForecastController(ILogger<WeatherForecastController> logger, IServerImpl serverImpl)
  {
    _logger = logger;
    _serverImpl = serverImpl;
  }
  ...
}

Is there any workaround to have it working? are those problems bug in asp-core or what am i doing wrong?

Thanks in advance


Get this bounty!!!

#StackBounty: #asp.net-core #.net-core #appsettings Can we use the ASPNET_REGIIS command to encrypt sections of the appsettings.json as…

Bounty: 200

When working with asp.net we can encrypt parts of the asp.net console application’s app.config file by following these steps:-

1- Rename the app.config to web.config >> run this command >>

ASPNET_REGIIS -pef "<<customAppSettingsGroup>>/<<customAppSettings>>" "C:projectsMSEMSEMSE"

2- Rename the web.config back to app.config….

Now inside asp.net core we do not have app.config, instead we have the appsettings.json.. so my question is if we can encrypt parts of the appsettings.json using the above approach? If the answer is No, then what are the approaches to encrypt sections of the appsettings.json?

Thanks


Get this bounty!!!