// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); var routeBuilder = new RouteBuilder(app); //routeBuilder.MapGet("", context => context.Response.WriteAsync("Hello from Routing")); routeBuilder.MapGet("sub", context => context.Response.WriteAsync("Hello from sub!")); routeBuilder.MapGet("item/{id:int}", context => context.Response.WriteAsync($"Id: {context.GetRouteValue("id")}")); routeBuilder.MapGet("item/{itemName}", context => context.Response.WriteAsync($"Item: {context.GetRouteValue("itemName")}")); app.UseRouter(routeBuilder.Build()); app.UseMvc(); }
public void Configure(IApplicationBuilder builder) { var endpoint1 = new DelegateRouteEndpoint(async (context) => await context .HttpContext .Response .WriteAsync( "match1, route values -" + context.RouteData.Values.Print())); var endpoint2 = new DelegateRouteEndpoint(async (context) => await context .HttpContext .Response .WriteAsync("Hello, World!")); var routeBuilder = new RouteBuilder(); routeBuilder.DefaultHandler = endpoint1; routeBuilder.ServiceProvider = builder.ApplicationServices; routeBuilder.AddPrefixRoute("api/store"); routeBuilder.MapRoute("defaultRoute", "api/constraint/{controller}", null, new { controller = "my.*" }); routeBuilder.MapRoute("regexStringRoute", "api/rconstraint/{controller}", new { foo = "Bar" }, new { controller = new RegexRouteConstraint("^(my.*)$") }); routeBuilder.MapRoute("regexRoute", "api/r2constraint/{controller}", new { foo = "Bar2" }, new { controller = new RegexRouteConstraint( new Regex("^(my.*)$", RegexOptions.None, TimeSpan.FromSeconds(10))) }); routeBuilder.MapRoute("parameterConstraintRoute", "api/{controller}/{*extra}", new { controller = "Store" }); routeBuilder.AddPrefixRoute("hello/world", endpoint2); routeBuilder.MapLocaleRoute("en-US", "store/US/{action}", new { controller = "Store" }); routeBuilder.MapLocaleRoute("en-GB", "store/UK/{action}", new { controller = "Store" }); routeBuilder.AddPrefixRoute("", endpoint2); builder.UseRouter(routeBuilder.Build()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Verbose); app.UseIISPlatformHandler(); var routeBuilder = new RouteBuilder(); routeBuilder.ServiceProvider = app.ApplicationServices; routeBuilder.Routes.Add(new TemplateRoute( new HelloRouter(), "hello/{name:alpha}", app.ApplicationServices.GetService<IInlineConstraintResolver>())); var endpoint1 = new DelegateRouter(async (context) => await context .HttpContext .Response .WriteAsync("Hello world! Route Values: " + string.Join("", context.RouteData.Values))); routeBuilder.DefaultHandler = endpoint1; routeBuilder.MapRoute( "Track Package Route", "package/{operation:regex(track|create|detonate)}/{id:int}"); app.UseRouter(routeBuilder.Build()); // demonstrate link generation var trackingRouteCollection = new RouteCollection(); trackingRouteCollection.Add(routeBuilder.Routes[1]); // "Track Package Route" app.Run(async (context) => { var dictionary = new RouteValueDictionary { {"operation","create" }, {"id",123} }; var vpc = new VirtualPathContext(context, null, dictionary, "Track Package Route"); context.Response.ContentType = "text/html"; await context.Response.WriteAsync("Menu<hr/>"); await context.Response.WriteAsync(@"<a href='" + trackingRouteCollection.GetVirtualPath(vpc).VirtualPath + "'>Create Package 123</a><br/>"); }); }
public static IBuilder UseMvc([NotNull] this IBuilder app, [NotNull] Action<IRouteBuilder> configureRoutes) { var routes = new RouteBuilder { DefaultHandler = new MvcRouteHandler(), ServiceProvider = app.ApplicationServices }; routes.Routes.Add(AttributeRouting.CreateAttributeMegaRoute( routes.DefaultHandler, app.ApplicationServices)); configureRoutes(routes); return app.UseRouter(routes.Build()); }
public static void UseScriptConsole(this IApplicationBuilder app, IServiceCollection theServices) { var appS = app.ApplicationServices; var scriptManager = new ScriptManager(); var services = new ServiceCollection(); services.Clear(); foreach (var s in theServices) services.Insert(0, s); services.AddInstance<ScriptManager>(scriptManager); var fp = new DebugFileProvider(new EmbeddedFileProvider(typeof(ScriptConsoleBuilderExtensions).Assembly, "ScriptConsole")); services .AddMvc() .AddControllersAsServices(new[] { typeof(ScriptConsoleController), typeof(HomeController) }) .AddRazorOptions(r => r.FileProvider = fp); services.AddLogging(); var provider = services.BuildServiceProvider(); app.Map("/ScriptConsole", builder => { var routeBuilder = new RouteBuilder() { DefaultHandler = new MvcRouteHandler(), ServiceProvider = new ShadowedServiceProvider(provider, app.ApplicationServices) }; routeBuilder.MapRoute("ScriptConsole", "{action}", new { controller = "ScriptConsole", action = "Index" }); routeBuilder.MapRoute("ScriptConsoleX", "{controller}/{action}", new { controller = "ScriptConsole", action = "Index" }); var route = routeBuilder.Build(); builder.Use(next => { return async (context) => { context.ApplicationServices = new ShadowedServiceProvider(provider, context.ApplicationServices); context.RequestServices = new ShadowedServiceProvider(provider, context.RequestServices); await route.RouteAsync(new RouteContext(context)); }; }); }); }
public void Configure(IApplicationBuilder app) { var endpoint1 = new RouteHandler((c) => { return c.Response.WriteAsync($"match1, route values - {string.Join(", ", c.GetRouteData().Values)}"); }); var endpoint2 = new RouteHandler((c) => c.Response.WriteAsync("Hello, World!")); var routeBuilder = new RouteBuilder(app) { DefaultHandler = endpoint1, }; routeBuilder.MapRoute("api/status/{item}", c => c.Response.WriteAsync($"{c.GetRouteValue("item")} is just fine.")); routeBuilder.MapRoute("localized/{lang=en-US}", b => { b.Use(next => async (c) => { var culture = new CultureInfo((string)c.GetRouteValue("lang")); #if DNX451 Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; #else CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; #endif await next(c); }); b.Run(c => c.Response.WriteAsync($"What would you do with {1000000m:C}?")); }); routeBuilder.AddPrefixRoute("api/store", endpoint1); routeBuilder.AddPrefixRoute("hello/world", endpoint2); routeBuilder.MapLocaleRoute("en-US", "store/US/{action}", new { controller = "Store" }); routeBuilder.MapLocaleRoute("en-GB", "store/UK/{action}", new { controller = "Store" }); routeBuilder.AddPrefixRoute("", endpoint2); app.UseRouter(routeBuilder.Build()); }
public static IApplicationBuilder UseMicrohand(this IApplicationBuilder app, Action<IRouteBuilder> configureRoutes, params Func<IEnumerable<IMessageHandler>>[] handlers) { var container = app.ApplicationServices.GetService<IServicesContainer>(); var registry = app.ApplicationServices.GetService<IHandlersRegistry>(); var routes = new RouteBuilder { DefaultHandler = new MicrohandlersRouter(registry, container), ServiceProvider = app.ApplicationServices, }; configureRoutes(routes); foreach (var reg in handlers) foreach (var h in reg()) registry.Register(h); return app.UseRouter(routes.Build()); }
/// <summary> /// Adds MVC to the <see cref="IApplicationBuilder"/> request execution pipeline. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/>.</param> /// <param name="configureRoutes">A callback to configure MVC routes.</param> /// <returns>The <paramref name="app"/>.</returns> public static IApplicationBuilder UseMvc( [NotNull] this IApplicationBuilder app, [NotNull] Action<IRouteBuilder> configureRoutes) { // Verify if AddMvc was done before calling UseMvc // We use the MvcMarkerService to make sure if all the services were added. MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices); var routes = new RouteBuilder { DefaultHandler = new MvcRouteHandler(), ServiceProvider = app.ApplicationServices }; configureRoutes(routes); // Adding the attribute route comes after running the user-code because // we want to respect any changes to the DefaultHandler. routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute( routes.DefaultHandler, app.ApplicationServices)); return app.UseRouter(routes.Build()); }
private static IRouter GetRouter( IServiceProvider services, string mockRouteName, string mockTemplateValue) { var routeBuilder = new RouteBuilder(); routeBuilder.ServiceProvider = services; var target = new Mock<IRouter>(MockBehavior.Strict); target .Setup(router => router.GetVirtualPath(It.IsAny<VirtualPathContext>())) .Callback<VirtualPathContext>(context => context.IsBound = true) .Returns<VirtualPathContext>(context => null); routeBuilder.DefaultHandler = target.Object; routeBuilder.MapRoute(string.Empty, "{controller}/{action}/{id}", new RouteValueDictionary(new { id = "defaultid" })); routeBuilder.MapRoute("namedroute", "named/{controller}/{action}/{id}", new RouteValueDictionary(new { id = "defaultid" })); var mockHttpRoute = new Mock<IRouter>(); mockHttpRoute .Setup(mock => mock.GetVirtualPath(It.Is<VirtualPathContext>(c => string.Equals(c.RouteName, mockRouteName)))) .Callback<VirtualPathContext>(c => c.IsBound = true) .Returns(new VirtualPathData(mockHttpRoute.Object, mockTemplateValue)); routeBuilder.Routes.Add(mockHttpRoute.Object); return routeBuilder.Build(); }
public void Action_RouteValueInvalidation_DoesNotAffectActionAndController_ActionPassedInRouteValues() { // Arrage var services = GetServices(); var routeBuilder = new RouteBuilder() { DefaultHandler = new PassThroughRouter(), ServiceProvider = services, }; routeBuilder.MapRoute( "default", "{first}/{controller}/{action}", new { second = "default", controller = "default", action = "default" }); var actionContext = services.GetService<IActionContextAccessor>().ActionContext; actionContext.RouteData.Values.Add("first", "a"); actionContext.RouteData.Values.Add("controller", "Store"); actionContext.RouteData.Values.Add("action", "Buy"); actionContext.RouteData.Routers.Add(routeBuilder.Build()); var urlHelper = CreateUrlHelper(services); // Act // // In this test the 'first' route value has changed, meaning that *normally* the // 'controller' value could not be used. However 'controller' and 'action' are treated // specially by UrlHelper. var url = urlHelper.Action(action: null, values: new { first = "b", action = "Checkout" }); // Assert Assert.NotNull(url); Assert.Equal("/b/Store/Checkout", url); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseStatusCodePages(subApp => { subApp.Run(async context => { context.Response.ContentType = "text/html"; await context.Response.WriteAsync($"Error @ {context.Response.StatusCode}"); }); }); } logFactory.AddConsole(LogLevel.Trace); logFactory.AddSerilog(); var logger = logFactory.CreateLogger<Startup>(); logger.LogTrace("Trace msg"); logger.LogDebug("Debug msg"); logger.LogInformation("Info msg"); logger.LogWarning("Warn msg"); logger.LogError("Error msg"); logger.LogCritical("Critical msg"); app.UseMiddleware<RequestIdMiddleware>(); //app.Run(ctx => //{ // //throw new Exception("some error"); // //ctx.Response.StatusCode = 500; // return Task.FromResult(0); //}); //app.UseIISPlatformHandler(); //app.UseFileServer(); var router = new RouteBuilder(app) .MapGet("", async ctx => await ctx.Response.WriteAsync("Hello from routing")) .MapGet("sub", async ctx => await ctx.Response.WriteAsync("Hello from sub")) .MapGet("item/{id:int}", ctx => ctx.Response.WriteAsync($"Item ID: {ctx.GetRouteValue("id")}")) ; app.UseRouter(router.Build()); app.UseMvc(); //app.UseRequestCulture(); //app.Run(async ctx => await ctx.Response.WriteAsync($"Hello {CultureInfo.CurrentCulture.DisplayName}")); //app.Run(async ctx => await ctx.Response.WriteAsync($"{Configuration["greeting"]}")); }
private static IRouter GetRouter(string mockRouteName, string mockTemplateValue) { var rt = new RouteBuilder(); var target = new Mock<IRouter>(MockBehavior.Strict); target .Setup(e => e.GetVirtualPath(It.IsAny<VirtualPathContext>())) .Callback<VirtualPathContext>(c => { rt.ToString(); c.IsBound = true; }) .Returns<VirtualPathContext>(rc => null); rt.DefaultHandler = target.Object; var serviceProviderMock = new Mock<IServiceProvider>(); var accessorMock = new Mock<IOptionsAccessor<RouteOptions>>(); accessorMock.SetupGet(o => o.Options).Returns(new RouteOptions()); serviceProviderMock.Setup(o => o.GetService(typeof(IInlineConstraintResolver))) .Returns(new DefaultInlineConstraintResolver(serviceProviderMock.Object, accessorMock.Object)); rt.ServiceProvider = serviceProviderMock.Object; rt.MapRoute(string.Empty, "{controller}/{action}/{id}", new RouteValueDictionary(new { id = "defaultid" })); rt.MapRoute("namedroute", "named/{controller}/{action}/{id}", new RouteValueDictionary(new { id = "defaultid" })); var mockHttpRoute = new Mock<IRouter>(); mockHttpRoute.Setup(mock => mock.GetVirtualPath(It.Is<VirtualPathContext>(c => string.Equals(c.RouteName, mockRouteName) ))) .Returns(mockTemplateValue); rt.Routes.Add(mockHttpRoute.Object); return rt.Build(); }
/// <summary> /// Runs the <see cref="TemplateRouteFetcher"/> with the specified route configuration. /// </summary> /// <param name="configure">Function to configure routes</param> /// <returns>List of routes returned from the route fetcher</returns> private static IList<RouteInfo> RunFetcher(Action<RouteBuilder> configure) { var routes = new RouteBuilder(); var serviceProvider = new Mock<IServiceProvider>(); serviceProvider.Setup(x => x.GetService(typeof(IInlineConstraintResolver))).Returns( new Mock<IInlineConstraintResolver>().Object ); routes.ServiceProvider = serviceProvider.Object; routes.DefaultHandler = new Mock<IRouter>().Object; configure(routes); var router = routes.Build(); var routeData = new RouteData(); routeData.Routers.Add(router); var fetcher = new TemplateRouteFetcher(new Mock<IConstraintsProcessor>().Object, new RouteTemplateParser()); return fetcher.GetRoutes(routeData).ToList(); }