简体   繁体   中英

Run Website from asp.net core console app

I have a console application that will be a service, it has a website to configure the service.

I have built my website and when i run that project it works fine.

I referenced my web project in the console application and inside there i use the following code to start the website.

    Task.Factory.StartNew(new Action(() => Website.Program.Main(null)), TaskCreationOptions.LongRunning);

my code in the website program class is

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseUrls("http://0.0.0.0:1234");              
}

The issue i have is the website now cannot find the css files and javascript files in wwwRoot, i tried publishing the application to the debug folder of the console application but this did not work. if i don't publish there is only dll files in the debug folder of the console application if i do publish all the files are there but the views cannot find them.

I am using ~ in the the views to find files.

Ideally I want a service that can be installed host its own website and API without it showing in the local computers IIS or need to enable IIS through windows features.

edit Startup.cs

  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<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddAuthentication(opt =>
        {
            opt.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            opt.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            opt.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            options.Cookie.Name = "TmiginScheme";
            options.LoginPath = "/Account/Login";
            options.LogoutPath = "/Account/Logout";
            options.AccessDeniedPath = "/Home/AccessDenied";
            options.ExpireTimeSpan = TimeSpan.FromDays(14);
            options.SlidingExpiration = true;
        });
        services.AddDistributedMemoryCache();
        services.AddSession();

        services.Configure<SettingsViewModel>(Configuration.GetSection("Settings"));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSession();
        app.UseAuthentication();

        var cookiePolicyOptions = new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.Strict,
        };

        app.UseCookiePolicy(cookiePolicyOptions);
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

    app.UseCookiePolicy();

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

A temporary fix, I was publishing to debug folder direct, I needed to publish to netcoreapp2.2 folder with razor compile disabled. This is still not an ideal solution to publish the website into the root of the console application if anyone has a more simple deployment.

Within Program.Main , set the current directory as the content root path prior to the call to CreateWebHostBuilder .

Also, this article could be a good approach for hosting your ASP.NET Core website in a Windows service: Host ASP.NET Core in a Windows Service

More Details

When you use the app.UseStaticFiles() middleware, the application expects to find static files within wwwroot (the "Web Root" directory) by default .

But to know about wwwroot , the application must first know its base path, the content root path

which

determines where ASP.NET Core begins searching for content files, such as MVC views

and which

  • needs to be set when running in a Windows service ( or when spawning as a long-running task from another program )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM