本文整理汇总了C#中Microsoft.AspNetCore.Hosting.WebHostBuilder.Build方法的典型用法代码示例。如果您正苦于以下问题:C# WebHostBuilder.Build方法的具体用法?C# WebHostBuilder.Build怎么用?C# WebHostBuilder.Build使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.AspNetCore.Hosting.WebHostBuilder
的用法示例。
在下文中一共展示了WebHostBuilder.Build方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main(string[] args)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json");
var configuration = configBuilder.Build();
var hostBuilder = new WebHostBuilder();
// set urls and environment
hostBuilder
.UseUrls(configuration["urls"])
.UseEnvironment(configuration["environment"]);
// set other common things
hostBuilder
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
var host = hostBuilder.Build();
host.Run();
}
示例2: Main
public static void Main(string[] args)
{
try
{
var host = new WebHostBuilder()
.UseKestrel(options =>
{
options.UseHttps(@"..\..\certificates\localhost_ssl.pfx", "[email protected]");
options.NoDelay = true;
//I use this to get rid of SSL errors, feel free to remove it.
IConnectionFilter prevFilter = options.ConnectionFilter ?? new NoOpConnectionFilter();
options.ConnectionFilter = new IgnoreSslErrorsConnectionFilter(prevFilter);
}
)
.UseUrls("https://localhost:5000")
.UseContentRoot(Directory.GetCurrentDirectory());
host.UseStartup<Startup>();
var webHost = host.Build();
webHost.Run();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
示例3: Run
public virtual Task Run(IPEndPoint http, IPEndPoint https, CancellationToken cancelToken) {
var urls = BuildUrls(http, https);
var hostBuilder = new WebHostBuilder();
// .UseContentRoot(Directory.GetCurrentDirectory())
ConfigureBuilder(hostBuilder);
hostBuilder.UseUrls(urls.ToArray());
var webHost = hostBuilder.Build();
return TaskExt.StartLongRunningTask(() => webHost.Run(cancelToken), cancelToken);
}
示例4: Main
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseKestrel()
.UseStartup<Startup>();
//launch the website!
host.Build().Run();
}
示例5: Run
public virtual Task Run(IPEndPoint http, IPEndPoint https, CancellationToken cancelToken) {
var hostBuilder = new WebHostBuilder();
// .UseContentRoot(Directory.GetCurrentDirectory())
ConfigureBuilder(hostBuilder);
var urls = new List<string>();
if ((http == null) && (https == null))
throw new CannotOpenApiPortException("No HTTP or HTTPS ports available");
if (http != null)
urls.Add(http.ToHttp());
if (https != null)
urls.Add(https.ToHttps());
hostBuilder.UseUrls(urls.ToArray());
var webHost = hostBuilder.Build();
return TaskExt.StartLongRunningTask(() => webHost.Run(cancelToken), cancelToken);
}
示例6: Main
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore.Web");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.WebListener", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseWebListener(options =>
{
options.ListenerSettings.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.ListenerSettings.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseWebListener();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
示例7: Main
public static void Main(string[] args)
{
ArgsConfig = new ConfigurationBuilder().AddCommandLine(args).Build();
var configFile = ArgsConfig["config"];
if (string.IsNullOrEmpty(configFile))
{
Console.WriteLine("No Config File");
}
else
{
var hostBuilder = new WebHostBuilder()
.UseKestrel()
.UseConfiguration(ArgsConfig)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
var appConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(configFile).Build();
var urls = appConfig["Data:App:urls"].Split(new char[] { ';', ',', ' ' });
hostBuilder.UseUrls(urls);
hostBuilder.Build().Run();
}
}
示例8: Main
// Entry point for the application.
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
ConfigureSerilog(configuration);
ConfigureShutdownHandler();
var builder = new WebHostBuilder()
.UseConfiguration(configuration)
.UseKestrel()
.UseStartup<Startup>();
#if DEBUG
var log = Log.ForContext<Program>();
var webroot = FindWebRoot();
log.Warning("Running in Debug mode, hosting static files from '{0}'.", webroot);
builder.UseWebRoot(webroot);
#endif
var host = builder.Build();
host.Run(ShutdownCancellationTokenSource.Token);
}
示例9: Main
// Entry point for the application.
public static void Main(string[] args)
{
var webHostBuilder = new WebHostBuilder()
.UseStartup<Startup>()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration();
var webHost = webHostBuilder.Build();
webHost.Run();
}
开发者ID:OneBitSoftware,项目名称:Microsoft.AspNetCore.Authentication.ActiveDirectory,代码行数:12,代码来源:Startup.cs
示例10: CreateWebHost
public static IWebHost CreateWebHost(HttpsConnectionFilterOptions httpsOptions) {
var webHostBuilder = new WebHostBuilder()
.UseLoggerFactory(_loggerFactory)
.UseConfiguration(Configuration)
.UseKestrel(options => {
if (httpsOptions != null) {
options.UseHttps(httpsOptions);
}
//options.UseConnectionLogging();
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
var webHost = webHostBuilder.Build();
var serverAddresses = webHost.ServerFeatures.Get<IServerAddressesFeature>();
string pipeName = _startupOptions.WriteServerUrlsToPipe;
if (pipeName != null) {
NamedPipeClientStream pipe;
try {
pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out);
pipe.Connect(10000);
} catch (IOException ex) {
_logger.LogCritical(0, ex, Resources.Critical_InvalidPipeHandle, pipeName);
throw;
} catch (TimeoutException ex) {
_logger.LogCritical(0, ex, Resources.Critical_PipeConnectTimeOut, pipeName);
throw;
}
var applicationLifetime = webHost.Services.GetService<IApplicationLifetime>();
applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => {
using (pipe) {
string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses);
_logger.LogTrace(Resources.Trace_ServerUrlsToPipeBegin, pipeName, Environment.NewLine, serverUriStr);
var serverUriData = Encoding.UTF8.GetBytes(serverUriStr);
pipe.Write(serverUriData, 0, serverUriData.Length);
pipe.Flush();
}
_logger.LogTrace(Resources.Trace_ServerUrlsToPipeDone, pipeName);
}));
}
return webHost;
}
示例11: Start
/// <summary>
/// Starts listening at the specified port.
/// </summary>
public void Start()
{
Startup.Listener = this;
m_host = new WebHostBuilder();
HttpsConnectionFilterOptions httpsOptions = new HttpsConnectionFilterOptions();
httpsOptions.CheckCertificateRevocation = false;
httpsOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate;
httpsOptions.ServerCertificate = m_serverCert;
httpsOptions.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
m_host.UseKestrel(options =>
{
options.NoDelay = true;
options.UseHttps(httpsOptions);
});
m_host.UseContentRoot(Directory.GetCurrentDirectory());
m_host.UseStartup<Startup>();
m_host.Build();
m_host.Start(Utils.ReplaceLocalhost(m_uri.ToString()));
}
示例12: Main
public static int Main(string[] args)
{
// Add command line configuration source to read command line parameters.
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
Server = config["server"] ?? "Kestrel";
var builder = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(config)
.UseStartup<Startup>();
// The default listening address is http://localhost:5000 if none is specified.
// Replace "localhost" with "*" to listen to external requests.
// You can use the --urls flag to change the listening address. Ex:
// > dotnet run --urls http://*:8080;http://*:8081
// Uncomment the following to configure URLs programmatically.
// Since this is after UseConfiguraiton(config), this will clobber command line configuration.
//builder.UseUrls("http://*:8080", "http://*:8081");
// If this app isn't hosted by IIS, UseIISIntegration() no-ops.
// It isn't possible to both listen to requests directly and from IIS using the same WebHost,
// since this will clobber your UseUrls() configuration when hosted by IIS.
// If UseIISIntegration() is called before UseUrls(), IIS hosting will fail.
builder.UseIISIntegration();
if (string.Equals(Server, "Kestrel", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Running demo with Kestrel.");
builder.UseKestrel(options =>
{
if (config["threadCount"] != null)
{
options.ThreadCount = int.Parse(config["threadCount"]);
}
});
}
else if (string.Equals(Server, "WebListener", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Running demo with WebListener.");
builder.UseWebListener(options =>
{
// AllowAnonymous is the default WebListner configuration
options.Listener.AuthenticationManager.AuthenticationSchemes =
AuthenticationSchemes.AllowAnonymous;
});
}
else
{
Console.WriteLine($"Error: Unknown server value: '{Server}'. The valid server options are 'Kestrel' and 'WebListener'.");
Console.WriteLine("IIS cannot be specified at runtime since it does not support self-hosting.");
return 1;
}
// ASPNETCORE_PORT is the port that IIS proxies requests to.
if (Environment.GetEnvironmentVariable($"ASPNETCORE_PORT") != null)
{
if (string.Equals(Server, "WebListener", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Error: WebListener cannot be used with the ASP.NET Core Module for IIS.");
return 1;
}
Server = "IIS/Kestrel";
Console.WriteLine("Hosted by IIS.");
}
var host = builder.Build();
host.Run();
return 0;
}
示例13: Main
public static void Main(string[] args)
{
Console.WriteLine($"OmniSharp: {string.Join(" ", args)}");
var applicationRoot = Directory.GetCurrentDirectory();
var serverPort = 2000;
var logLevel = LogLevel.Information;
var hostPID = -1;
var transportType = TransportType.Http;
var otherArgs = new List<string>();
var plugins = new List<string>();
var enumerator = args.GetEnumerator();
while (enumerator.MoveNext())
{
var arg = (string)enumerator.Current;
if (arg == "-s")
{
enumerator.MoveNext();
applicationRoot = Path.GetFullPath((string)enumerator.Current);
}
else if (arg == "-p")
{
enumerator.MoveNext();
serverPort = int.Parse((string)enumerator.Current);
}
else if (arg == "-v")
{
logLevel = LogLevel.Debug;
}
else if (arg == "--hostPID")
{
enumerator.MoveNext();
hostPID = int.Parse((string)enumerator.Current);
}
else if (arg == "--stdio")
{
transportType = TransportType.Stdio;
}
else if (arg == "--plugin")
{
enumerator.MoveNext();
plugins.Add((string)enumerator.Current);
}
else
{
otherArgs.Add((string)enumerator.Current);
}
}
Environment = new OmnisharpEnvironment(applicationRoot, serverPort, hostPID, logLevel, transportType, otherArgs.ToArray());
var config = new ConfigurationBuilder()
.AddCommandLine(new[] { "--server.urls", "http://localhost:" + serverPort });
var writer = new SharedConsoleWriter();
var builder = new WebHostBuilder()
.UseConfiguration(config.Build())
.UseEnvironment("OmniSharp")
.UseStartup(typeof(Startup))
.ConfigureServices(serviceCollection =>
{
serviceCollection.AddSingleton<IOmnisharpEnvironment>(Environment);
serviceCollection.AddSingleton<ISharedTextWriter>(writer);
serviceCollection.AddSingleton<PluginAssemblies>(new PluginAssemblies(plugins));
serviceCollection.AddSingleton<IOmnisharpAssemblyLoader>(new OmnisharpAssemblyLoader());
});
if (transportType == TransportType.Stdio)
{
builder.UseServer(new StdioServer(Console.In, writer));
}
else
{
builder.UseServer("Microsoft.AspNetCore.Server.Kestrel");
}
using (var app = builder.Build())
{
app.Start();
var appLifeTime = app.Services.GetRequiredService<IApplicationLifetime>();
Console.CancelKeyPress += (sender, e) =>
{
appLifeTime.StopApplication();
e.Cancel = true;
};
if (hostPID != -1)
{
try
{
var hostProcess = Process.GetProcessById(hostPID);
hostProcess.EnableRaisingEvents = true;
hostProcess.OnExit(() => appLifeTime.StopApplication());
}
catch
//.........这里部分代码省略.........
示例14: Main
public static void Main(string[] args)
{
Args = args;
Console.WriteLine();
Console.WriteLine("ASP.NET Core Benchmarks");
Console.WriteLine("-----------------------");
Console.WriteLine($"Current directory: {Directory.GetCurrentDirectory()}");
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.AddJsonFile("hosting.json", optional: true)
.Build();
Server = config["server"] ?? "Kestrel";
var webHostBuilder = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(config)
.UseStartup<Startup>()
.ConfigureServices(services => services
.AddSingleton(new ConsoleArgs(args))
.AddSingleton<IScenariosConfiguration, ConsoleHostScenariosConfiguration>()
.AddSingleton<Scenarios>()
);
if (String.Equals(Server, "Kestrel", StringComparison.OrdinalIgnoreCase))
{
var threads = GetThreadCount(config);
webHostBuilder = webHostBuilder.UseKestrel((options) =>
{
if (threads > 0)
{
options.ThreadCount = threads;
}
});
}
else if (String.Equals(Server, "WebListener", StringComparison.OrdinalIgnoreCase))
{
webHostBuilder = webHostBuilder.UseWebListener();
}
else
{
throw new InvalidOperationException($"Unknown server value: {Server}");
}
var webHost = webHostBuilder.Build();
Console.WriteLine($"Using server {Server}");
Console.WriteLine($"Server GC is currently {(GCSettings.IsServerGC ? "ENABLED" : "DISABLED")}");
var nonInteractiveValue = config["NonInteractive"];
if (nonInteractiveValue == null || !bool.Parse(nonInteractiveValue))
{
StartInteractiveConsoleThread();
}
webHost.Run();
}