Scott Hanselman

Exploring a minimal WebAPI with ASP.NET Core

July 26, '16 Comments [9] Posted in ASP.NET | ASP.NET Web API
Sponsored By

They are still working on the "dotnet new" templates, but you can also get cool templates from "yo aspnet" usingn Yeoman. The generator-aspnet package for Yeoman includes an empty web app, a console app, a few web app flavors, test projects, and a very simple Web API application that returns JSON and generally tries to be RESTful.

yo aspnet

The startup.cs is pretty typical and basic. The Startup constructor sets up the Configuration with an appsettings.json file and add a basic Console logger. Then by calling "UseMvc()" we get to use all ASP.NET Core which includes both centralized routing and attribute routing. ASP.NET Core's controllers are unified now, so there isn't a "Controller" and "ApiController" base class. It's just Controller. Controllers that return JSON or those that return Views with HTML are the same so they get to share routes and lots of functionality.

public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
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, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseMvc();
}
}

Then you can make a basic controller and use Attribute Routing to do whatever makes you happy. Just by putting [HttpGet] on a method makes that method the /api/Values default for a simple GET.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace tinywebapi.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

If we run this with "dotnet run" and call/curl/whatever to http://localhost:5000/api/Values we'd get a JSON array of two values by default. How would we (gasp!) add XML as a formatting/serialization option that would respond to a request with an Accept: application/xml header set?

I'll add "Microsoft.AspNetCore.Mvc.Formatters.Xml" to project.json and then add one method to ConfigureServices():

services.AddMvc()
        .AddXmlSerializerFormatters();

Now when I go into Postman (or curl, etc) and do a GET with Accept: application/xml as a header, I'll get the same object expressed as XML. If I ask for JSON, I'll get JSON.

 Postman is a great way to explore WebAPIs

If I like, I can create my own custom formatters and return whatever makes me happy. PDFs, vCards, even images.

Next post I'm going to explore the open source NancyFx framework and how to make minimal WebAPI using Nancy under .NET Core.


Sponsor: Thanks to Aspose for sponsoring the feed this week! Aspose makes programming APIs for working with files, like: DOC, XLS, PPT, PDF and countless more.  Developers can use their products to create, convert, modify, or manage files in almost any way. Aspose is a good company and they offer solid products. Check them out, and download a free evaluation!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Exploring dotnet new with .NET Core

July 18, '16 Comments [33] Posted in ASP.NET | ASP.NET MVC | DotNetCore | Open Source
Sponsored By

I'm very enjoying the "dotnet" command line. Mostly I do "dotnet new" and then add to the default Hello World app with the Visual Studio Code editor. Recently, though, I realized that the -t "type" and -l "lang" options are there and I wasn't use them. I think they are a little awkward, in that you have to:

dotnet new -t Web

when I think it should be more like dotnet new [type] as in

dotnet new web

What do you think? I find the -t a little heavy. I like the idea of "web" being empty, and "web/mvc" or "web/webapi" having more fleshed out stuff. Even "web/angular," you get the idea. Sound off in the comments. Regardless, there's cool templating tooling coming, I hear, but for now there's more there than I realized.

Of course, there's the default "dotnet new" which is a Hello World console app with a program.cs and project.json. In the future I think it will just run the app, and you'll have to do something like -v verbosity to get the details that we don't usually need to see.

C:\Users\scott\Desktop\test\console>dotnet run
Project console (.NETCoreApp,Version=v1.0) will be compiled because expected outputs are missing
Compiling console for .NETCoreApp,Version=v1.0

Compilation succeeded.
0 Warning(s)
0 Error(s)

Time elapsed 00:00:01.1591124

Hello World!

You can add -l (lang) to it and "dotnet new -l F#" and get an F# Console app rather than a C# one:

C:\Users\scott\Desktop\test\fsharp>dotnet run fabu!
Project fsharp (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Hello World!
[|"fabu!"|]

C:\Users\scott\Desktop\test\fsharp>type Program.fs
// Learn more about F# at http://fsharp.org

open System

[<EntryPoint>]
let main argv =
printfn "Hello World!"
printfn "%A" argv
0 // return an integer exit code

There's also "dotnet new -t lib" which is super basic and gives you a quick new project with a Class1 and an Empty Method. Not so useful, but good to know.

You can also "dotnet new -t xunittest" to make a new test project. Nice that this is built-in! Now I just "dotnet test" after a "dotnet restore" and I get test results!

xUnit.net .NET CLI test runner (64-bit win10-x64)
Discovering: testing
Discovered: testing
Starting: testing
Finished: testing
=== TEST EXECUTION SUMMARY ===
testing Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.146s
SUMMARY: Total: 1 targets, Passed: 1, Failed: 0.

Side Note: If the folder name of the project is the same as one of the dependencies, it can confuse the resolver. For example, I did my new test project in a folder creatively named "XUnit." This is also the name of a dependency. I got the error: Errors in C:\Users\scott\Desktop\test\xunit\project.json Cycle detected:  xunit (>= 1.0.0) -> xunit (>= 2.1.0) -> xunit (>= 2.1.0). Note that 1.0.0 there. That's my project, which is 1.0.0. Solution? Rename my project's containing folder.

There's ASP.NET Core Hello World, which is "dotnet new -t Web." This will give you a nice simple ASP.NET Core app with some simple defaults that's setup for bower, gulp, and npm usage. I anticipate we'll see varying levels of what folks consider "complete."

yo aspnet: dotnet new -t web isn't the only way to make a new ASP.NET Core project from the command line (CLI). You can also use the Yeoman generator or "yo aspnet" to make very interesting projects, as well as create your own generators. In fact, Steve Sanderson has some impressive generators like his "aspnet-spa" generator for making Angular, React, and Knockout Single Page Apps (SPA) with ASP.NET Core.

image

All these generators work on Windows, Mac, and Linux, of course. I believe the intent is to reconcile them all such that Visual Studio proper and Visual Studio Code via the CLI will all get the same "File | New Project" results. Visual Studio will still be more "visual" but everything you can do in one world can and should be possible in another.


Sponsor: Big thanks to Redgate for sponsoring the feed this week. Have you got SQL fingers? Try SQL Prompt and you’ll be able to write, refactor, and reformat SQL effortlessly in SSMS and Visual Studio. Find out more!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

.NET Core 1.0 is now released!

June 27, '16 Comments [69] Posted in ASP.NET | Open Source
Sponsored By
Code .NET in the Cloud!

I feel like it's the culmination of all these years of work in .NET and Open Source. This is why I came to work at Microsoft; we wanted to open source as much as we could and build a community around .NET and open source at Microsoft. 15 years and the work of thousands of people later, today we released .NET Core 1.0.

Take a moment and head over to http://dot.net and check out the download page. It's got a really nice place you can try out C# directly in the browser without having to install anything! There's also a great C# Tutorial with interactive browser-based tools as well.

.NET Core 1.0 runs on Windows, Mac, and several flavors of Linux including RedHat Enterprise Linux and Ubuntu. It supports C#, VB, and F# and modern constructs like generics, Language Integrated Query (LINQ), async support and more. The Core Runtime, libraries, compiler, languages and tools are all open source on GitHub where contributions are accepted, tested and fully supported.

Getting started with .NET Core

What is .NET Core? Here's some details from the .NET Blog:

.NET Core is a new cross-platform .NET product. The primary points of .NET Core are:

  • Cross-platform: Runs on Windows, macOS and Linux.
  • Flexible deployment: Can be included in your app or installed side-by-side user- or machine-wide.
  • Command-line tools: All product scenarios can be exercised at the command-line.
  • Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.
  • Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. Documentation is licensed under CC-BY. .NET Core is a .NET Foundation project.
  • Supported by Microsoft: .NET Core is supported by Microsoft, per .NET Core Support

.NET Core is composed of the following parts:

  • A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interop and other basic services.
  • A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities.
  • A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.
  • The ‘dotnet’ app host, which is used to launch .NET Core apps. It selects and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in the same way.

Blogs

Here are the major blogs carrying the announcement.

We are also releasing .NET documentation today at docs.microsoft.com, the new documentation service for Microsoft. The documentation you see there is just a start. You can follow our progress at core-docs on GitHub. ASP.NET Core documentation is also available and open source.

Have fun!


Sponsor: Build servers are great at compiling code and running tests, but not so great at deployment. When you find yourself knee-deep in custom scripts trying to make your build server do something it wasn't meant to, give Octopus Deploy a try.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Adding a Custom Inline Route Constraint in ASP.NET Core 1.0

June 23, '16 Comments [22] Posted in ASP.NET | ASP.NET MVC
Sponsored By

ASP.NET supports both attribute routing as well as centralized routes. That means that you can decorate your Controller Methods with your routes if you like, or you can map routes all in one place.

Here's an attribute route as an example:

[Route("home/about")]
public IActionResult About()
{
//..
}

And here's one that is centralized. This might be in Startup.cs or wherever you collect your routes. Yes, there are better examples, but you get the idea. You can read about the fundamentals of ASP.NET Core Routing in the docs.

routes.MapRoute("about", "home/about",
new { controller = "Home", action = "About" });

A really nice feature of routing in ASP.NET Core is inline route constraints. Useful URLs contain more than just paths, they have identifiers, parameters, etc. As with all user input you want to limit or constrain those inputs. You want to catch any bad input as early on as possible. Ideally the route won't even "fire" if the URL doesn't match.

For example, you can create a route like

files/{filename}.{ext?}

This route matches a filename or an optional extension.

Perhaps you want a dateTime in the URL, you can make a route like:

person/{dob:datetime}

Or perhaps a Regular Expression for a Social Security Number like this (although it's stupid to put a SSN in the URL ;) ):

user/{ssn:regex(d{3}-d{2}-d{4})}

There is a whole table of constraint names you can use to very easily limit your routes. Constraints are more than just types like dateTime or int, you can also do min(value) or range(min, max).

However, the real power and convenience happens with Custom Inline Route Constraints. You can define your own, name them, and reuse them.

Lets say my application has some custom identifier scheme with IDs like:

/product/abc123

/product/xyz456

Here we see three alphanumerics and three numbers. We could create a route like this using a regular expression, of course, or we could create a new class called CustomIdRouteConstraint that encapsulates this logic. Maybe the logic needs to be more complex than a RegEx. Your class can do whatever it needs to.

Because ASP.NET Core is open source, you can read the code for all the included ASP.NET Core Route Constraints on GitHub. Marius Schultz has a great blog post on inline route constraints as well.

Here's how you'd make a quick and easy {customid} constraint and register it. I'm doing the easiest thing by deriving from RegexRouteConstraint, but again, I could choose another base class if I wanted, or do the matching manually.

namespace WebApplicationBasic
{
public class CustomIdRouteConstraint : RegexRouteConstraint
{
public CustomIdRouteConstraint() : base(@"([A-Za-z]{3})([0-9]{3})$")
{
}
}
}

In your ConfigureServices in your Startup.cs you just configure the route options and map a string like "customid" with your new type like CustomIdRouteConstraint.

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.Configure<RouteOptions>(options =>
options.ConstraintMap.Add("customid", typeof(CustomIdRouteConstraint)));
}

Once that's done, my app knows about "customid" so I can use it in my Controllers in an inline route like this:

[Route("home/about/{id:customid}")]
public IActionResult About(string customid)
{
// ...
return View();
}

If I request /Home/About/abc123 it matches and I get a page. If I tried /Home/About/999asd I would get a 404! This is ideal because it compartmentalizes the validation. The controller doesn't need to sweat it. If you create an effective route with an effective constraint you can rest assured that the Controller Action method will never get called unless the route matches.

If the route doesn't fire it's a 404

Unit Testing Custom Inline Route Constraints

You can unit test your custom inline route constraints as well. Again, take a look at the source code for how ASP.NET Core tests its own constraints. There is a class called ConstrainsTestHelper that you can borrow/steal.

I make a separate project and setup xUnit and the xUnit runner so I can call "dotnet test."

Here's my tests that include all my "Theory" attributes as I test multiple things using xUnit with a single test. Note we're using Moq to mock the HttpContext.

public class TestProgram
{

[Theory]
[InlineData("abc123", true)]
[InlineData("xyz456", true)]
[InlineData("abcdef", false)]
[InlineData("totallywontwork", false)]
[InlineData("123456", false)]
[InlineData("abc1234", false)]
public void TestMyCustomIDRoute(
string parameterValue,
bool expected)
{
// Arrange
var constraint = new CustomIdRouteConstraint();

// Act
var actual = ConstraintsTestHelper.TestConstraint(constraint, parameterValue);

// Assert
Assert.Equal(expected, actual);
}
}

public class ConstraintsTestHelper
{
public static bool TestConstraint(IRouteConstraint constraint, object value,
Action<IRouter> routeConfig = null)
{
var context = new Mock<HttpContext>();

var route = new RouteCollection();

if (routeConfig != null)
{
routeConfig(route);
}

var parameterName = "fake";
var values = new RouteValueDictionary() { { parameterName, value } };
var routeDirection = RouteDirection.IncomingRequest;
return constraint.Match(context.Object, route, parameterName, values, routeDirection);
}
}

Now note the output as I run "dotnet test". One test with six results. Now I'm successfully testing my custom inline route constraint, as a unit. in isolation.

xUnit.net .NET CLI test runner (64-bit .NET Core win10-x64)
Discovering: CustomIdRouteConstraint.Test
Discovered: CustomIdRouteConstraint.Test
Starting: CustomIdRouteConstraint.Test
Finished: CustomIdRouteConstraint.Test
=== TEST EXECUTION SUMMARY ===
CustomIdRouteConstraint.Test Total: 6, Errors: 0, Failed: 0, Skipped: 0, Time: 0.328s

Lots of fun!


Sponsor: Working with DOC, XLS, PDF or other business files in your applications? Aspose.Total Product Family contains robust APIs that give you everything you need to create, manipulate and convert business files along with many other formats in your applications. Stop struggling with multiple vendors and get everything you need in one place with Aspose.Total Product Family. Start a free trial today.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

.NET Core 1.0 RC2 - Upgrading from previous versions

May 19, '16 Comments [38] Posted in ASP.NET
Sponsored By

.NET Core at http://dot.net.NET Core RC2 is out, it's open source, and it's on multiple platforms. I'm particularly proud of the cool vanity domain we got for it. http://dot.net. ;) It makes me smile.

Here's the important blog posts to check out:

Head over to http://dot.net and check it out. A great aspect of .NET Core is that everything it does is side-by-side. You can work with it without affecting your existing systems. Be sure also explore the complete .NET Downloads Page for all the manual downloads as well as SHA hashes.

The best way to develop with .NET Core on Windows is to download the Visual Studio official MSI Installer and the latest NuGet Manager extension for Visual Studio. If you don't have Visual Studio already, you can download Visual Studio Community 2015 for free.

We'll have documentation and insights on how to moving from ASP.NET 4.x over to ASP.NET Core 1.0 soon, but for now I've collected these resources for folks who are upgrading from previous versions of .NET Core and ASP.NET Core (the framework formerly new as ASP.NET 5).

Enjoy!


Sponsor: Build servers are great at compiling code and running tests, but not so great at deployment. When you find yourself knee-deep in custom scripts trying to make your build server do something it wasn't meant to, give Octopus Deploy a try.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Page 1 of 167 in the ASP.NET category Next Page

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.