ASP.Net Core application from scratch

blog-asp-net

07 Nov

Asp.Net Core is a toolset for creating web applications for .Net Core. Although the name contains ASP.Net this is an absolutely new product for web-developers.

It is simple and clear and it allows you to write more compact code. Web applications created with Asp.Net Core are cross platform and can be ran without IIS (Internet Information Server) and Azure (but can work with them too).

Lets stop talking and create a simple ASP.Net Core application without from scratch. We will not use any code generators (like yeoman) nor any IDE. No ugly web.config files. Even Windows is not required (but can be used). Only terminal and your favorite text editor. .Net Core SDK should be pre-installed too of cause.

Create new .Net Core console application in empty directory by command

Open the created file project.json and add to field dependencies next values:

In project.json

The first line will add Asp.Net Core support to our application. The second line will allow the web application to be self-hosted (with Kestrel web server).

From Command line Run:

That will install ASP.Net core packages.

Copy/Paste into Program.cs

From Command line Run:

Hooray, we did it! Open browser to: http://localhost:5000 and see … nothing.

Let’s make our web application show some text.

Program.cs

Run the application again. Good. Now we can see text “Hello ASP.Net Core” in the browser.

MVC

Let’s make our application more complex. First add MVC support. Open project.json and add into dependencies line

Run

to install ASP.Net MVC libraries.

Now change class Startup

Now our application is MVC-powered.

Lets create a controller. Create directory controllers and add file DemoController.cs there with content

DemoController.cs

Attribute [Route("[controller]")] says that our controller will handle routes with pathes /demo (demo is taken from name of DemoController).

Lets run our application and make GET request to http://localhost:5000/demo. We will see text “Hello ASP.Net Core”.

Let’s make this action a bit more async.

In DemoController.cs

Ok, let’s make action which can extract query parameters from request. Add next method to DemoController.

In DemoController.cs

Run the application and make GET request to http://localhost:5000/demo/query?text=hello to see result. Replace [FromQuery] by [FromQuery(Name="q")]. Now our application will handle GET requests like http://localhost:5000/demo/query?q=hello.

Lets extract parameter from request url. Add next method

In DemoController.cs

Now we can make GET requests like /demo/123.

What about posting form data? Lets add this method.

In DemoController.cs

where Item is

Re-run the application and make POST request to /demo with form (application/x-www-form-urlencoded) text=hello. If you omit field text in such request the property Text of item in method Create() will be null.

Lets handle json data. Replace [FromForm] in method Create by [FromBody]. Now make POST request to /demo with json content {"Text": "hello"} You will see same result.
But if we post in json field text instead of Text the item.Text will be null. Lets fix that. Open Program.cs and change ConfigureServices of StartUp by

In Program.cs

Now our app will work with camel-cased names in json data right.

Dependency injection

Dependency injection is a technique for achieving loose coupling between objects and their collaborators, or dependencies. Rather than directly instantiating collaborators, or using static references. The objects a class needs in order to perform its actions are provided to the class in some fashion. ASP.Net Core has support of dependency injection in the box. Lets see how it works.

Lets add a “useful” service

Now register our service in ConfigureServices of Startup by line

Thats all. Now we can use instance of IMyUsefullService in constructor of any our controller and instance of MyUsefullService will be used there.

Here we showed a small piece of ASP.Net Core infrastructure. The basis of any ASP.Net Core application is small kernel which includes middleware, dependency injection, logging, configuration, and error handling support. Other possibilities (like MVC, Views, Databases, etc supports) are implemented as external libraries.

You can use only things you explicitly require. Each such library extends web application by new middlewares (their registering code is often hidden in extension methods of IApplicationBuilder) and services (like database context). You can split your own code to middlewares and share it with different applications.

Say hello to more compact and clear code of web applications in .Net Core universe. Start to use ASP.Net Core in new projects.

Andrey Belchikov
Andrey Belchikov
blogs@bandwidth.com

Andrey is a Software Developer at Bandwidth. He started his work as embedded-device programmer on C/C++. Then he switched to web development on C#. Now he knows JavaScript, Ruby, Golang and has experience in frontend, backend and mobile. He found to learn something new in IT to follow his credo: "you don't live if you don't like to study". While not at work he can be found taking photos, and playing with his child.

3 Comments
  • p.chin
    Posted at 22:35h, 07 November Reply

    what about the next steps…like connect to a EF6 db? some pages to collect data from users and post them to the db? that’s where I get lost, not the first few steps where everyone is posting examples.

  • Jure
    Posted at 17:25h, 08 November Reply

    Great article for learning the basics. Would also appreciate an article on using the logger, database and other basic stuff. Thank you

  • Davis
    Posted at 17:14h, 09 November Reply

    I was trying to follow along with this but get hung up here;
    // GET /demo
    [HttpGet]
    public async Task Index()
    {
    // call any async methods with await here
    return Task.FromResult(“Hello ASP.Net Core”);
    }

    And I get this error when trying to run

    controllers/DemoController.cs(10,27): error CS1983: The return type of an async method must be void, Task or Task
    controllers/DemoController.cs(10,22): error CS0246: The type or namespace name ‘Task’ could not be found (are you missing a using directive or an assembly reference?)

Post A Comment