{"id":5898,"date":"2018-02-18T22:40:05","date_gmt":"2018-02-18T22:40:05","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=5898"},"modified":"2018-02-19T16:55:58","modified_gmt":"2018-02-19T16:55:58","slug":"more-asp-net-core-with-c","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/more-asp-net-core-with-c\/","title":{"rendered":"More ASP.NET Core with C#"},"content":{"rendered":"<p>In the previous post I looked into the F# Giraffe library which makes writing all sorts of web request\/response code pretty simple. This in turn is built on top of the existing functionality within ASP.NET Core.<\/p>\n<p>Let&#8217;s again look at the bare bones code from running up Kestrel adding code to the pipeline<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing Microsoft.AspNetCore;\r\nusing Microsoft.AspNetCore.Builder;\r\nusing Microsoft.AspNetCore.Hosting;\r\nusing Microsoft.AspNetCore.Http;\r\n\r\nnamespace KestrelTest\r\n{\r\n    public class Startup\r\n    {\r\n        public void Configure(\r\n            IApplicationBuilder applicationBuilder,\r\n            IHostingEnvironment hostingEnvironment)\r\n        {\r\n        }\r\n    }\r\n\r\n    class Program\r\n    {\r\n        static void Main(string&#x5B;] args)\r\n        {\r\n            WebHost.CreateDefaultBuilder()\r\n                .UseStartup&lt;Startup&gt;()\r\n                .UseKestrel()\r\n                .Build()\r\n                .Run();\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>Within the Configure method we can start adding code to respond to different routes using the <em>Map<\/em> method, for example add the following to the Configure method<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\napplicationBuilder.Map(&quot;\/hello&quot;, app =&gt;\r\n{\r\n   app.Run(async ctx =&gt;\r\n   {\r\n      var request = \r\n         ctx.Request.Path.HasValue ? \r\n            ctx.Request.Path.Value.Substring(1) : \r\n            String.Empty;\r\n       await ctx.Response.WriteAsync(&quot;Hello &quot; + request);\r\n   });\r\n});\r\napplicationBuilder.Map(&quot;\/error&quot;, app =&gt;\r\n{\r\n   app.Run(ctx =&gt; \r\n      Task.FromResult(\r\n         ctx.Response.StatusCode = 404) \r\n   );\r\n});\r\n<\/pre>\n<p><em>Note: The code is somewhat basic, obviously you would probably want to write some better code for extracting partial paths etc. from the routes\/maps. However we&#8217;ll be covering a better alternative to this sort of code later in the post.<\/em><\/p>\n<p>In the above we&#8217;ve created the equivalent of two &#8220;routes&#8221;. The first handles URL&#8217;s along the line of localhost:5000\/hello\/World where the return would become &#8220;Hello World&#8221;. The second route simply responds with a 404 for the URL localhost:5000\/error.<\/p>\n<p>We can also (as you&#8217;d expect) handle queries within our URL, so let&#8217;s say we expect this format URL, http:\/\/localhost:5000\/hello?name=World, then we can amend our \/hello code to the following<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\napplicationBuilder.Map(&quot;\/hello&quot;, app =&gt;\r\n{\r\n   app.Run(async ctx =&gt;\r\n   {\r\n      await ctx.Response.WriteAsync(\r\n         &quot;Hello &quot; + ctx.Request.Query&#x5B;&quot;name&quot;]);\r\n   });\r\n});\r\n<\/pre>\n<p>These pieces of code write responses, but we can also insert code into the pipeline which doesn&#8217;t write to the response but instead might add debug\/logging code. Other examples of usage might include (as per <a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/fundamentals\/middleware\/?tabs=aspnetcore2x#writing-middleware\" rel=\"noopener\" target=\"_blank\">Writing Middleware<\/a>) changes to the culture for the user response.<\/p>\n<p>Here&#8217;s a simple example of such code, this is a little contrived as we&#8217;re going to (in essence) redirect calls to \/hello path. Just place the following code before the applicationBuilder.Map method in the above<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\napplicationBuilder.Use(async (ctx, next) =&gt;\r\n{\r\n   if (ctx.Request.Path.Value == &quot;\/hello&quot;)\r\n   {\r\n      ctx.Request.Path = new PathString(&quot;\/error&quot;);\r\n   }\r\n   await next.Invoke();\r\n});\r\n<\/pre>\n<p><em>Note: there are redirect\/URL rewriting capabilities already in ASP.NET Core, see URL <a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/fundamentals\/url-rewriting?tabs=aspnetcore2x\" rel=\"noopener\" target=\"_blank\">Rewriting Middleware in ASP.NET Core<\/a>.<\/em><\/p>\n<p><strong>Routing<\/strong><\/p>\n<p>In the previous example we demonstrated using the Map method to route our calls but ASP.NET Core libraries already supply a routing middleware which handles a lot of the standard routing type of functionality we&#8217;d expect. We can add the routing services by adding a method to the Startup class like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic void ConfigureServices(\r\n   IServiceCollection services)\r\n{\r\n   services.AddRouting();\r\n}\r\n<\/pre>\n<p>Now the Configure method should look like this<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic void Configure(\r\n   IApplicationBuilder applicationBuilder,\r\n   IHostingEnvironment hostingEnvironment)\r\n{\r\n   var routes = new RouteBuilder(applicationBuilder);\r\n   routes.MapGet(&quot;hello\/{name}&quot;, ctx =&gt;\r\n   {\r\n      var name = ctx.GetRouteValue(&quot;name&quot;);\r\n      return ctx.Response.WriteAsync($&quot;Hello {name}&quot;);\r\n   });\r\n\r\n   applicationBuilder.UseRouter(routes.Build());\r\n}\r\n<\/pre>\n<p>The RouteBuilder handles the routing in a more helpful\/useful manner. Don&#8217;t forget to use the line <em>applicationBuilder.UseRouter(routes.Build());<\/em> or you&#8217;ll find that the routes are not registered and hence your code will never get called.<\/p>\n<p><strong>References<\/strong><\/p>\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/fundamentals\/middleware\/?tabs=aspnetcore2x\" rel=\"noopener\" target=\"_blank\">ASP.NET Core Middleware<\/a><a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/fundamentals\/routing\" rel=\"noopener\" target=\"_blank\">Routing in ASP.NET Core<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the previous post I looked into the F# Giraffe library which makes writing all sorts of web request\/response code pretty simple. This in turn is built on top of the existing functionality within ASP.NET Core. Let&#8217;s again look at the bare bones code from running up Kestrel adding code to the pipeline using Microsoft.AspNetCore; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[200,3,202],"tags":[],"class_list":["post-5898","post","type-post","status-publish","format-standard","hentry","category-asp-net-core","category-c","category-kestrel"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5898","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=5898"}],"version-history":[{"count":9,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5898\/revisions"}],"predecessor-version":[{"id":5917,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5898\/revisions\/5917"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=5898"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=5898"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=5898"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}