2

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.

Travellogger
  • 79
  • 1
  • 6
  • 1
    Use the debugger. What string are you passing into `GetBytes`? – Dai Jan 22 '18 at 22:08
  • 4
    Can you please provide code not images? Thanks ^^ – Meikel Jan 22 '18 at 22:09
  • Can you run it from command line? – Meikel Jan 22 '18 at 22:09
  • The project runs perfectly on Windows?, please, provide the code of program.cs ? – makitocode Jan 22 '18 at 22:10
  • Hi Thanks for the reply. I added the whole code of program.cs on the question itself. I also made a new MVC project in my mac (the same code was generated above) and it worked perfectly well. – Travellogger Jan 22 '18 at 22:25
  • How much of the same code, what is different between the two? For instance, you have a SQL Connection but you aren't building or linking to a appsettings.json file. I assume a difference exists. You can't get a connection string from a file it can't access. – Greg Jan 23 '18 at 15:12
  • Hi Greg, we were using a database for the identity and our own database and both were accessible to the mac as well. Do I need to load a separate SQL Server driver on my MAC? – Travellogger Jan 24 '18 at 18:06
  • In my case, running my .NETCore 2.0 web app from VS for Mac opens browser with localhost:5000 but page is blank. Any idea? – pixel Oct 04 '18 at 21:26

2 Answers2

1

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));
Greg
  • 11,302
  • 2
  • 48
  • 79
  • 1
    Hi Sir, I'm not sure why .net core hosting is not installed... we tried to make a new core2 mvc project on the mac and it worked perfectly. Need your help as well on what data do you need so i can attach it properly on the initial question? Would you like me to include the startup cs file and the libraries im using? – Travellogger Jan 23 '18 at 08:32
  • 1
    Yes, startup would be helpful. Non obstructed code line with error. By default they don’t install it, Windows by default doesn’t install it until version 17.5.4 I believe. If you go their website, download the hosting bundle, I bet you it’s not installed. – Greg Jan 23 '18 at 13:19
0

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 :)

Travellogger
  • 79
  • 1
  • 6