Trying to run a .net core 2 web application in Mac

1.9k Views Asked by At

I have made an mvc .net core2 application in Windows and copied the whole thing in my MAC (highSierra 10.13.2) and tried to run it using VS for MAC (7.3.3 build 5).

vs.net 7.3.3 build 5 mac

It compiles perfectly both on the PC and my MAC. But it won't launch on my MAC

I'm getting a System.ArgumentNullException in the program.cs file.

The said file was created by default on VS.NET Windows Which contains this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace [projectname namespace]
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();


    }
}

String reference not set to an instance of a string

Just for reference here is my startup

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.AddDbContext<ApplicationDbContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

        string SecretKey = "replaceme";
        SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

            ValidateAudience = true,
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(configureOptions =>
        {
            configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            configureOptions.TokenValidationParameters = tokenValidationParameters;
            configureOptions.SaveToken = true;
        });

        // api user claim policy
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
        });

        services.AddAuthentication().AddFacebook(facebookOptions =>
        {
            facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
            facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            facebookOptions.SaveTokens = true;
            facebookOptions.Scope.Add("gender");
            facebookOptions.Scope.Add("email");
            facebookOptions.Scope.Add("public_profile");
            facebookOptions.Scope.Add("user_birthday");
        });

        services.AddAuthentication().AddGoogle(googleOptions =>
        {
            googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
            googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
        });


        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
        services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Travellogger Web API", Description = ".NET Core 2" }); });
        //services.Configure<Helpers.TravelloggerSettings>(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();



        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger();
        app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core 2 API"); });
    }
}

NOTE: I created a sample mvc core2 app on mac which has the same code above (generated automatically) and it works perfectly well hence I didn't download additional runtime for core 2 from Microsoft as suggested below...

Do I need todo an additional configuration?

I tried searching here on StackOverflow, but couldn't find any results.

Would appreciate it if you could give me a link if this has been asked before.

2

There are 2 best solutions below

2
On

Your information doesn't fully address the issue, but your problem more than likely is stemmed from the following:

  • Asp.Net Core 2 Runtime & Hosting Bundle need to be installed. (Not in VS dmg)
  • The project relies on a reverse proxy (usually with IIS on Windows) or HttpSys

If you haven't downloaded those, then the project won't work. The hosting may need to be configured, while on Window's Visual Studio preconfigure's IIS to act as a reverse proxy to debug.

The reason I'm recommending those, is line seventeen where your error exist, is the Build portion of your host. So either an issue exists in the startup and has bubbled, or on the instantiation of Build. Which produces the following:

Create a host using an instance of WebHostBuilder. This is typically performed in the app's entry point, the Main method. In the project templates, Main is located in Program.cs. A typical Program.cs calls CreateDefaultBuilder to start setting up a host:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
  • CreateDefaultBuilder performs the following tasks: Configures Kestrel as the web server. For the Kestrel default options, see the Kestrel options section of Kestrel web server implementation in ASP.NET Core.
  • Sets the content root to the path returned by Directory.GetCurrentDirectory.
  • Loads optional configuration from:
    • appsettings.json.
    • appsettings.{Environment}.json.
    • User secrets when the app runs in the Development environment.
    • Environment variables.
    • Command-line arguments.
  • Configures logging for console and debug output. Logging includes log filtering rules specified in a Logging configuration section of an appsettings.json or appsettings.{Environment}.json file.
  • When running behind IIS, enables IIS integration. Configures the base path and port the server listens on when using the ASP.NET Core Module. The module creates a reverse proxy between IIS and Kestrel. Also configures the app to capture startup errors. For the IIS default options, see the IIS options section of Host ASP.NET Core on Windows with IIS.

Update: If the code truly is the same, which I doubt. As I denoted above, you aren't telling the builder to access your appsettings.json file. Which would be code in the following:

var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();

Also, your error more then likely stems from this line:

string SecretKey = "replaceme";
        SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
0
On

It now works by disabling first JWT section on the startup config and the succeeding web api that uses authorizations.....

I didn't install the separate runtime from Microsoft

Here is the copy of a ConfigureServices in startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddAuthentication().AddFacebook(facebookOptions =>
        {
            facebookOptions.AppId = Configuration["Settings:Authentication:Facebook:AppId"];
            facebookOptions.AppSecret = Configuration["Settings:Authentication:Facebook:AppSecret"];
            facebookOptions.SaveTokens = true;
            facebookOptions.Scope.Add("gender");
            facebookOptions.Scope.Add("email");
            facebookOptions.Scope.Add("public_profile");
            facebookOptions.Scope.Add("user_birthday");
            //facebookOptions.UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email";
            //facebookOptions.BackchannelHttpHandler = new Helpers.FacebookBackChannelHandler();
            //https://stackoverflow.com/questions/32059384/why-new-fb-api-2-4-returns-null-email-on-mvc-5-with-identity-and-oauth-2
            //https://github.com/aspnet/Security/issues/435
        });

        services.AddAuthentication().AddGoogle(googleOptions =>
        {
            googleOptions.ClientId = Configuration["Settings:Authentication:Google:ClientId"];
            googleOptions.ClientSecret = Configuration["Settings:Authentication:Google:ClientSecret"];
        });


        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
        services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Web API", Description = ".NET Core 2" }); });

    }

The next item to solve is the JWT authentication :) Thanks guys :)