0

I have a .net core 2.2 api deployed on a CentOs. In my workspace, on Windows, the api runs just fine but when I try to run it on CentOS I get an Null exception.

I think the problem is with the JWT auth because if I try to comment out that configuration, the api runs ok. But with it I get the exception:

The error I get:

    [root@localhost ~]# /bin/dotnet /var/www/vhosts/prueba.com/prueba.dll
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at prueba.Startup.ConfigureServices(IServiceCollection services)
--- End of stack trace from previous location where exception was thrown     ---
   at     Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServic    eCollection services)
   at     Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at prueba.Program.Main(String[] args) in         C:\Users\user\source\repos\prueba\prueba\Program.cs:line 17

My StartUp class:

using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace prueba
{
    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.AddCors();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


        // Auto Mapper Configurations
        services.AddSingleton(typeof(Startup));

        //// configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                //ValidateIssuerSigningKey = true,
                //ValidateAudience = false,
                //ValidateIssuer = false,
                //IssuerSigningKeys = new List<SecurityKey> { signingKey },
                // Validate the token expiry
                ValidateLifetime = false,
                RequireExpirationTime = false
            };
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        //// configure DI for application services
        //services.AddScoped<IUserService, UserService>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // global cors policy
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // 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.UseAuthentication();
        app.UseMvc();
    }
}

}

I think this config shoud be just fine because when I run it in Visual studio I can get issue a token and connect with it but there is no way I can make it work in CentOs. By the way my CentOs version is 7 and I have installed the .net core 2.2 sdk.

Thank you very much!!

---------EDIT---------------------

This is my appsettings.json:

{
  "AppSettings": {
    "Secret": "ESTA_ES_MI_SECRET"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

I checked the option to be copied always when the project is compiled.

The way that I call my project is with: /bin/dotnet /var/www/vhosts/exchange.com/prueba.dll

BiancaP
  • 31
  • 1
  • 9
  • If I had to guess, and I have to, you didn't give enough details, `appSettingsSection` is `null` because you didn't copy the correct `appsettings.json` file, or you are not running the application from the correct directory. Try to first `cd var/www/vhosts/prueba.com` and then `dotnet prueba.dll` – Camilo Terevinto May 31 '19 at 15:34
  • @CamiloTerevinto thank you for your answer, I have updated my question – BiancaP May 31 '19 at 15:45

0 Answers0