C# 尝试在Mac中运行.net core 2 web应用程序

C# 尝试在Mac中运行.net core 2 web应用程序,c#,asp.net-core-2.0,.net-mac,C#,Asp.net Core 2.0,.net Mac,我在Windows中制作了一个mvc.net core2应用程序,并在我的MAC(highSierra 10.13.2)中复制了整个程序,并尝试使用VS for MAC(7.3.3 build 5)运行它 它可以在PC和MAC上完美编译。但它不会在我的MAC上启动 我在program.cs文件中得到一个System.ArgumentNullException 默认情况下,上述文件是在VS.NET Windows上创建的,其中包含以下内容: using System; using System.

我在Windows中制作了一个mvc.net core2应用程序,并在我的MAC(highSierra 10.13.2)中复制了整个程序,并尝试使用VS for MAC(7.3.3 build 5)运行它

它可以在PC和MAC上完美编译。但它不会在我的MAC上启动

我在
program.cs
文件中得到一个
System.ArgumentNullException

默认情况下,上述文件是在VS.NET Windows上创建的,其中包含以下内容:

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();


    }
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.Logging;
名称空间[项目名称名称空间]
{
公共课程
{
公共静态void Main(字符串[]args)
{
BuildWebHost(args.Run();
}
公共静态IWebHost BuildWebHost(字符串[]args)=>
WebHost.CreateDefaultBuilder(args)
.UseStartup()
.Build();
}
}

这是我的创业计划,仅供参考

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"); });
    }
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext,如下所示

是否需要进行其他配置?

我尝试在StackOverflow上搜索,但找不到任何结果


如果以前有人问过这个问题,请给我一个链接,我将不胜感激。

您的信息没有完全解决这个问题,但您的问题很可能是由以下原因造成的:

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

        Configuration = builder.Build();
  • 需要安装Asp.NETCore2运行时和主机包。(不在VSDMG中)
  • 该项目依赖于反向代理(通常在Windows上使用IIS)或HttpSys
如果尚未下载这些,则项目将无法工作。可能需要在Windows的Visual Studio预配置的IIS上配置宿主,以充当反向代理进行调试

我之所以推荐这些,是因为第17行中存在错误,是因为主机的
构建部分。因此,启动时存在问题并冒泡,或者是
构建部分的实例化出现问题。这会产生以下结果:

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

        Configuration = builder.Build();
使用WebHostBuilder实例创建主机。这通常是 在应用程序的入口点执行,即项目中的主要方法 模板,Main位于Program.cs中。典型的Program.cs调用 CreateDefaultBuilder开始设置主机:

此外,您的错误很可能来自以下几行:

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

它现在可以通过禁用启动配置上的第一个JWT部分和后续使用授权的web api来工作

我没有从安装单独的运行时

这是startup.cs中ConfigureServices的副本

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" }); });

    }
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.AddAuthentication().AddFacebook(facebook选项=>
{
facebookOptions.AppId=配置[“设置:身份验证:Facebook:AppId”];
facebookOptions.AppSecret=配置[“设置:身份验证:Facebook:AppSecret”];
facebookOptions.SaveTokens=true;
facebookOptions.Scope.Add(“性别”);
facebookOptions.Scope.Add(“电子邮件”);
facebookOptions.Scope.Add(“public_profile”);
facebookOptions.Scope.Add(“用户生日”);
//facebookOptions.UserInformationEndpoint=”https://graph.facebook.com/v2.5/me?fields=id,姓名,电邮”;
//facebookOptions.BackchannelHttpHandler=新助手。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=配置[“设置:身份验证:Google:ClientId”];
googleOptions.ClientSecret=配置[“设置:身份验证:Google:ClientSecret”];
});
//添加应用程序服务。
services.AddTransient();
services.AddMvc();
services.AddSwaggerGen(c=>{c.SwaggerDoc(“v1”,new swashback.AspNetCore.Swagger.Info{Title=“Web API”,Description=“.NET Core 2”});});
}

下一个要解决的问题是JWT身份验证:)谢谢大家:)

使用调试器。你要传递什么字符串到
GetBytes
?你能提供代码而不是图像吗?谢谢^^你能从命令行运行它吗?项目在Windows上运行得很好吗?请提供program.cs的代码?你好,谢谢你的回复。我添加了我还在我的mac电脑上做了一个新的MVC项目(上面生成了相同的代码)它工作得非常好。您好,先生,我不知道为什么没有安装.net core主机…我们尝试在mac上制作一个新的core2 mvc项目,它工作得非常好。您还需要您的帮助,了解您需要什么数据,以便我可以在初始问题上正确地附加它?您希望我包括启动cs文件和我使用的库吗?是的s、 启动会很有帮助。无障碍代码行有错误。默认情况下他们不会安装,Windows默认情况下直到17.5.4版本才会安装。如果你访问他们的网站,请下载主机