如何在Windows中自托管ASP.NET Core Web App?

时间:2018-08-26 10:22:14

标签: c# asp.net asp.net-core asp.net-core-mvc

我可以成功地自行托管ASP.NET Core应用程序,而不是在IIS中托管。

但是现在我面临一个问题。

下面是我的.NET核心项目,它是一个控制台应用程序项目。

enter image description here

Program.cs:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using System;

namespace ConsoleAppCoreWeb
{
    class Program
    {
        static void Main(string[] args)
        {
            BuildWebHost(args).Run();
            Console.WriteLine("Please enter any key to exit");
            Console.ReadLine();
        }
        public static IWebHost BuildWebHost(string[] args) =>
           WebHost.CreateDefaultBuilder(args).UseUrls("http://localhost:5001")
                  .UseStartup<Startup>()
                  .Build();
    }
}

Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;


namespace ConsoleAppCoreWeb
{
    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()
        {
            // Includes support for Razor Pages and controllers.
            //services.AddMvc();
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.Run(context => context.Response.WriteAsync("hello world"));
        }
    }
}

一切正常,结果截图如下:

enter image description here

enter image description here

我按如下所示修改ConfigureServices类中的Startup方法后,出现了问题。

    public void ConfigureServices(IServiceCollection services)
    {
        // Includes support for Razor Pages and controllers.
        services.AddMvc();
    }

BuildWebHost类中调用Program方法时出现错误消息:

"The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection."

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

尝试从以下位置更改签名:

public void ConfigureServices(IServiceCollection services)

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    return services.BuildServiceProvider();
}