本文整理汇总了C#中IApplicationBuilder.Use方法的典型用法代码示例。如果您正苦于以下问题:C# IApplicationBuilder.Use方法的具体用法?C# IApplicationBuilder.Use怎么用?C# IApplicationBuilder.Use使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IApplicationBuilder
的用法示例。
在下文中一共展示了IApplicationBuilder.Use方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Configure
public void Configure(IApplicationBuilder app, ILoggerFactory logger)
{
logger.AddConsole(LogLevel.Information);
app.UseHttpLog();
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseMvc();
app.MapWhen(ctx => ctx.Request.Path.Value.Equals("/super-secret"), HandleSecret);
app.Use(async (context, next) =>
{
Console.WriteLine("1");
await next.Invoke();
Console.WriteLine("2");
});
app.Use(async (context, next) =>
{
Console.WriteLine("3");
await next.Invoke();
Console.WriteLine("4");
});
app.Run(async (context) =>
{
//throw new Exception("Something bad happened...");
await context.Response.WriteAsync(_configuration.Get<string>("HelloMessage"));
});
}
示例2: Configure
/* Boileplate code generated with new app
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
--- */
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello world!");
await next();
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(" This is sort of an echo Hello world!");
});
}
示例3: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
// For any requests coming in from '/dist/**/*' or '__webpack_hmr', we wan't to proxy those requests
// to our webpack dev server that is running.
// Make sure you have 'gulp dev' running before starting the .NET web stuff.
// NOTE: You may want to configure this to only run on a dev environment, and not production.
var proxyOptions = new OptionsWrapper<ProxyOptions>(new ProxyOptions
{
Host = "localhost",
Port = "5001"
});
app.Use(async (context, next) =>
{
if(!context.Request.Path.StartsWithSegments("/dist")
&& !context.Request.Path.StartsWithSegments("/__webpack_hmr"))
{
await next();
return;
}
var proxyMiddleware = new ProxyMiddleware(httpContext => next.Invoke(), proxyOptions);
await proxyMiddleware.Invoke(context);
});
app.UseJsEngine(); // this needs to be before MVC
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
示例4: Configure
public void Configure(IApplicationBuilder app)
{
// Request pipeline
app.UseWebSockets();
app.Use(HandleWebSocketsAsync);
app.UseMvc();
// Initialization
Task.Run(async () =>
{
await InitializeDatabaseAsync();
await InitializeServiceBrokerAsync(app.ApplicationServices);
})
.Wait();
// Background tasks
Task.Run(async () =>
{
await ProcessMessagesAsync(app.ApplicationServices);
});
}
示例5: Configure
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseIISPlatformHandler();
app.Use((context, next) =>
{
if (context.Request.Path.Equals("/Anonymous"))
{
return context.Response.WriteAsync("Anonymous?" + !context.User.Identity.IsAuthenticated);
}
if (context.Request.Path.Equals("/Restricted"))
{
if (context.User.Identity.IsAuthenticated)
{
return context.Response.WriteAsync(context.User.Identity.AuthenticationType);
}
else
{
return context.Authentication.ChallengeAsync();
}
}
if (context.Request.Path.Equals("/Forbidden"))
{
return context.Authentication.ForbidAsync(string.Empty);
}
if (context.Request.Path.Equals("/AutoForbid"))
{
return context.Authentication.ChallengeAsync();
}
if (context.Request.Path.Equals("/RestrictedNegotiate"))
{
if (string.Equals("Negotiate", context.User.Identity.AuthenticationType, System.StringComparison.Ordinal))
{
return context.Response.WriteAsync("Negotiate");
}
else
{
return context.Authentication.ChallengeAsync("Negotiate");
}
}
if (context.Request.Path.Equals("/RestrictedNTLM"))
{
if (string.Equals("NTLM", context.User.Identity.AuthenticationType, System.StringComparison.Ordinal))
{
return context.Response.WriteAsync("NTLM");
}
else
{
return context.Authentication.ChallengeAsync("NTLM");
}
}
return context.Response.WriteAsync("Hello World");
});
}
示例6: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IHostingEnvironment env, INodeServices nodeServices)
{
app.UseDeveloperExceptionPage();
// Dynamically transpile any .js files under the '/js/' directory
app.Use(next => async context => {
var requestPath = context.Request.Path.Value;
if (requestPath.StartsWith("/js/") && requestPath.EndsWith(".js")) {
var fileInfo = env.WebRootFileProvider.GetFileInfo(requestPath);
if (fileInfo.Exists) {
var transpiled = await nodeServices.Invoke<string>("./Node/transpilation.js", fileInfo.PhysicalPath, requestPath);
await context.Response.WriteAsync(transpiled);
return;
}
}
// Not a JS file, or doesn't exist - let some other middleware handle it
await next.Invoke(context);
});
app.UseStaticFiles();
loggerFactory.AddConsole();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
示例7: Configure
public void Configure(IApplicationBuilder app, ILoggerFactory LoggerFactory, ILogger<Startup> logger)
{
LoggerFactory.AddConsole(LogLevel.Information);
app.Use(async (context, next) =>
{
var s = ("[Pipeline] Request to:" + context.Request.Path);
logger.LogInformation(s);
Debug.WriteLine(s);
await next();
});
//app.Use(async (context, next) =>
//{
// var s = ("Headers:\n" + JsonConvert.SerializeObject(context.Request.Headers, Formatting.Indented));
// logger.LogInformation(s);
// Debug.WriteLine(s);
// s = ("Body:\n" + JsonConvert.SerializeObject(context.Request.Form, Formatting.Indented));
// logger.LogInformation(s);
// Debug.WriteLine(s);
// await next();
//});
app.UseStaticFiles();
app.UseErrorPage();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Page", action = "Index" });
});
}
示例8: Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment environment)
{
// Route all unknown requests to app root
app.Use(async (context, next) =>
{
await next();
// If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
// Rewrite request to use app root
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/app/index.html";
await next();
}
});
// Serve wwwroot as root
app.UseFileServer();
var nodeModulesPath =
Path.Combine(environment.ContentRootPath, "node_modules");
createFolderIfItDoesNotExist(nodeModulesPath);
// Serve /node_modules as a separate root (for packages that use other npm modules client side)
app.UseFileServer(new FileServerOptions()
{
// Set root of file server
FileProvider = new PhysicalFileProvider(nodeModulesPath),
// Only react to requests that match this path
RequestPath = "/node_modules",
// Don't expose file system
EnableDirectoryBrowsing = false
});
}
示例9: Configure
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<RequestDurationMiddleware>();
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hi Cancel!<br/>");
await next.Invoke();
await context.Response.WriteAsync("<br/>I'm done.");
});
app.Map("/diagnostics", c =>
{
c.Run(async ctx =>
{
var feature = ctx.GetFeature<IHttpConnectionFeature>();
await ctx.Response.WriteAsync("Hello Diagnostics test from " + feature.RemoteIpAddress);
});
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
示例10: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type, x-xsrf-token" });
if (context.Request.Method == "OPTIONS")
{
context.Response.StatusCode = 200;
}
else
{
await next();
}
});
//app.UseCors(p => p.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:5000").AllowCredentials().WithHeaders("Access-Control-Allow-Origin"));
app.UseMvc();
var token = app.ApplicationServices.GetService<IApplicationLifetime>().ApplicationStopped;
if (token != CancellationToken.None)
token.Register(() => ClusterHelper.Close());
}
示例11: Configure
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.Use(next => new TimeRecorderMiddleware(next).Invoke);
app.UseSession();
app.UseMvc(Router.Instance.Route);
}
示例12: Configure
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
LifetimeManager lifetimeManager,
InterpreterManager interpreterManager,
SecurityManager securityManager
) {
lifetimeManager.Initialize();
interpreterManager.Initialize();
app.UseWebSockets(new WebSocketOptions {
ReplaceFeature = true,
KeepAliveInterval = TimeSpan.FromMilliseconds(1000000000),
ReceiveBufferSize = 0x10000
});
var routeBuilder = new RouteBuilder(app, new RouteHandler(RemoteUriHelper.HandlerAsync));
routeBuilder.MapRoute("help_and_shiny", "remoteuri");
app.UseRouter(routeBuilder.Build());
app.UseBasicAuthentication(options => {
options.Events = new BasicEvents { OnSignIn = securityManager.SignInAsync };
});
app.Use((context, next) => {
if (!context.User.Identity.IsAuthenticated) {
return context.Authentication.ChallengeAsync();
} else {
return next();
}
});
app.UseMvc();
}
示例13: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.Use(async (context, next) =>
{
if (context.Request.IsHttps)
await next();
else
context.Response.Redirect($"https://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}", permanent: true);
});
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
示例14: Configure
public void Configure(IApplicationBuilder app)
{
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthentication = true;
options.LoginPath = new PathString("/");
});
app.UseOAuthAuthentication("GitHub-AccessToken", options =>
{
options.ClientId = _configuration.Get("GitHub:ClientId");
options.ClientSecret = _configuration.Get("GitHub:Secret");
options.CallbackPath = new PathString("/signin-github");
options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
options.TokenEndpoint = "https://github.com/login/oauth/access_token";
options.SaveTokensAsClaims = true;
options.Scope.Add("read:org");
options.Scope.Add("repo");
});
app.Use(async (context, next) =>
{
if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
{
await context.Authentication.ChallengeAsync("GitHub-AccessToken", new AuthenticationProperties() { RedirectUri = context.Request.Path.ToString() });
return;
}
await next();
});
app.UseMvcWithDefaultRoute();
}
示例15: Configure
public void Configure(IApplicationBuilder app)
{
//TJOwin.HealthCheck.AppBuilderExtensions.UseHealthCheck(null);
var config = new HealthCheckConfiguration();
app.UseHealthCheck(config);
app.Use(helloworldMiddleware);
}