Tutorials on Asp.net Core

Learn about Asp.net Core from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Release Management with ASP.Net Core and GitHub Actions

In this article, we will learn how to set up automated release creation for an ASP.Net Core project with GitHub ActionsRelease management can be a complicated beast at the best of times, and is notoriously hard to get right. Previously, shell scripts and batch files used to be the most common tools used for automation, and countless hours were spent trying to get them working as expected. This has changed in recent times, with platforms such as GitHub Actions providing a much simpler way of automating tasks and managing releases. In the last article , we have seen how GitHub Actions can be used to set up a pipeline for Continuous Integration (CI). In the following sections, we will build on that, and add a workflow that publishes release artifacts when new code is merged to the main branch. For the purposes of this tutorial, we will use a simple .NET Core console application. This can be created via the following command using the .NET CLI which is installed along with the SDK. We will use the GitHub repository that we created in the previous article, which already contains a GitHub Actions CI workflow that builds and runs unit tests on pushes to main and pull request branches. A tag is a label that can be applied to any commit in your repository for later identification. Tags are typically used to mark commits for releases. You can create a tag using the following commands in your terminal/command line. Tag names can be any arbitrary string, but are usually version numbers like v1.0.0 or v.1.1.2-beta5. When a tag has been published, it will appear in the 'Tags' section in your repository. You can then use the created tag to create a GitHub release - each release has a title, short description and attachments such as release notes, source code and built artifacts. In the next step, we will learn how to build our project and associate the built app code artifacts with the just-created release. Let us now create a release.yml file in the .github/workflows directory alongside the ci.yml workflow we have defined previously. We will use the release published event to trigger our workflow. This means our workflow will get triggered when a new release is published using the mechanism from the previous step. Let us now understand what this workflow does: We can now create a release using the steps described earlier. Let us first tag the last commit in our repo. I'll call the tag v1.0 . The tag will now appear in the 'Tags' section, and we can create a release from it. The release notes can be automatically populated based on the commits since the last tag. Once we hit publish, a release gets created on the 'Releases' page. Note that this only has the source code, and not the built artifacts from the tagged commit. Publishing the release also triggers our new workflow. When the workflow has finished, the built ZIP file and tarball are added to the release assets, and we have successfully released v1.0 of our app! 🎉 In this tutorial, we have learnt how to create and automate tasks around releases for an ASP.Net Core project using GitHub Actions. We built on concepts we learnt in the previous tutorial on CI with GitHub Actions . If you find yourself stuck at any point during the tutorial, you can view all the source code on my GitHub here . More detail on all the events that can be used to trigger GitHub Actions workflows can be found in the GitHub docs .

Thumbnail Image of Tutorial Release Management with ASP.Net Core and GitHub Actions

Continuous Integration (CI) with ASP.Net Core and GitHub Actions

In this article, we will learn how to set up a simple build workflow for an ASP.Net Core project with GitHub Actions.Modern apps often have large codebases with multiple teams of developers working across different geographical locations and time zones. In this scenario, it is of utmost importance to ensure that each change to the codebase works correctly not just in isolation, but in the context of all the existing code. This keeps quality levels high and guarantees the best possible experience for the app's users. Continuous Integration (CI) can be used to automatically run an array of checks on the codebase that could be triggered before code changes are merged, thus ensuring the quality of all released code. GitHub Actions is a powerful continuous integration (CI) and continuous delivery (CD) platform available for all code repositories hosted on GitHub. It allows you to build, test, and deploy your code on multiple platforms, right from your source code repository. GitHub Actions are triggered via GitHub workflows, which are YAML (either  *.yml  or  *.yaml ) files within the .github/workflows/ directory in your repository. A workflow references one or more GitHub Actions, run in a specified sequence to accomplish a given task. In the following sections, we will learn more about how GitHub Actions and workflows function, and understand how they can be used to automatically build, test, and release an ASP.Net Core project. For the purposes of this tutorial, let us use a simple .NET Core console application. We can create one using the .NET CLI which is installed along with the SDK. You can create a repository on GitHub and push the code created by the above command using the instructions in the GitHub docs . A .gitignore file can be added to ignore the build output and an optional readme file for documentation. At this stage, your GitHub repo should look somewhat like this: Now that we have our app code on GitHub, we can start creating our automated workflows. We can begin by defining a Continuous Integration(CI) workflow that will run each time code is committed to a PR branch or to main . Let us define a simple CI workflow with three steps that will install our project's NuGet dependencies, build it and run any tests, all using the dotnet CLI. We want this workflow to run on each commit to a PR branch or to main , and run on two platforms - Linux and Windows, to make sure our app works perfectly on both. As can be seen from the diagram above, each step in the workflow depends on the step before it, and can only run if the previous step is completed successfully. Now, we can create a .github/workflows directory and create a ci.yml file in there that defines this as a GitHub workflow. The YAML syntax is quite simple and readable and is easy to understand. Please refer to the comments inline in the below code block for more context. Let us now look at the structure of the workflow in detail: We've used the actions/checkout and actions/setup-dotnet predefined actions in our workflow. These, along with a wide variety of other actions are available in the GitHub Marketplace . If one isn't available for your specific purpose, you can create your own using either JavaScript or a Docker container. One of the great things about GitHub Actions is that the workflows are defined right alongside your source code. This means you can create, test, and refine new workflows on a branch before applying them to your main branch. Let us create a branch called add-ci-workflow , commit the workflow file that we have defined above in .github/workflows/ci.yml , and open a pull request to trigger the workflow. GitHub immediately recognizes the new workflow and starts the process of running the jobs defined in it. You should see status updates for each of the jobs appearing at the bottom of the pull request. You can then click through to view the details of each workflow run, where you can read through the console output from the various commands running on the build machine. This can also be accessed from the 'Actions' tab on your repository page. Once all checks have been completed, the branch can be merged into main . This will trigger a run of our workflow jobs against the newly merged code in main . A very important part of your CI setup is the idea of ensuring that only good code makes it to the main branch. To this end, GitHub allows you to set up rules that require certain GitHub Actions workflows have successfully completed before a branch can be merged. This can be used in conjunction with code reviews to keep quality levels high. The rule in the screenshot below specifies that pull requests are required for merges to main , and they can only be merged when our CI checks have succeeded. You can add a status badge for any GitHub Actions workflow in your repository to your readme file, which shows visitors and potential users of your repo the status of your CI/CD pipelines. This can be added using the URL scheme below and added as a markdown image URL in your readme: There are more parameters you can add to the URL, that are documented here . In this article, we have learned how to set up a continuous integration workflow for an ASP.NET Core app using GitHub Actions. We have also discovered how to leverage GitHub's branch protection rules with workflows to ensure only high-quality code makes it to the main branch. Most of the concepts we have explored around creating and running workflows are generic in nature, so you can apply them to any project with a different technology stack with the appropriate modifications. In an upcoming article, we will take things a step further and learn how to create releases and publish artifacts for ASP.Net Core projects with GitHub Actions workflows. All the example code used in this article is available on GitHub .

Thumbnail Image of Tutorial Continuous Integration (CI) with ASP.Net Core and GitHub Actions

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Building Your First ASP.NET Core RESTful API for Node.js Developers - Introduction (Part 1)

Over the past decade, many developers started their backend development journey with Node.js. What makes Node.js compelling to developers is the benefit of creating client-side and server-side applications with a single programming language: JavaScript. This convenience, along with the growing interest in frameworks written with modern programming languages like Golang and Rust, means more developers are less likely to branch out to older, more established technologies like ASP.NET. Developed and maintained by Microsoft, ASP.NET ( A ctive S erver P ages N etwork E nabled T echnologies) is a framework for creating dynamic web applications and services on the .NET platform . You can write ASP.NET applications with any .NET programming language: C#, F# or Visual Basic. ASP.NET is widely used across many industries, most notably, by large corporations and government agencies. Despite Microsoft's efforts to adapt ASP.NET to the rapidly evolving web development landscape, such as the release of ASP.NET MVC in 2009 in response to the popularity of MVC frameworks like Django and Ruby on Rails, ASP.NET continued to suffer from several limitations: To migrate away from ASP.NET's monolithic design, Microsoft re-implemented ASP.NET as a modular, cross-platform compatible, open-source framework named ASP.NET Core . Released in 2016 , ASP.NET Core comes with built-in support for dependency injection and provides... With these features, you can build and run lightweight web applications on Windows , Linux and macOS via the .NET Core runtime. In fact, developers can host their web applications not just on IIS, but also, Nginx, Docker, Apache and much more. This all makes ASP.NET Core applications suitable for containerization and optimized for cloud-based environments. For any missing functionality, you can fetch them as packages from NuGet . As the package manager for .NET, NuGet is equivalent to npm for Node.js. At its core, an ASP.NET Core application is a self-contained console application that self-hosts a web server (by default, the cross-platform web server Kestrel ), which processes incoming requests and passes them directly to the application. Once it finishes handling a request, the application passes the response to the web server, which sends the response directly to the client (or reverse proxy). Keeping the web server independent of the application this way makes testing and debugging much simpler, especially when compared to previous versions of ASP.NET where IIS directly executes the application's methods. So why might Node.js developers consider learning ASP.NET Core? In the latest round of TechEmpower benchmark, ASP.NET Core significantly outperforms Node.js, sending back almost nine times more plaintext responses per second. Below, I'm going to show you how to build your first ASP.NET Core RESTful API with C#, a strongly-typed, object-oriented language. Throughout this tutorial, I will relate concepts and patterns to those that you may have already encountered in an Express.js RESTful API. To get started, verify that you have the latest LTS version of the .NET Core SDK, v6, installed on your machine. The .NET Core SDK (Software Development Kit) consists of everything you need to create and run .NET applications: If your machine does not have the .NET Core SDK installed, then download the latest LTS version of the .NET Core SDK for your specific platform and follow the installation directions. Once installed, create a new directory named weather-api . Then, within this directory, create a new solution file: A solution file lists and tracks all of the projects that belong to a .NET Core application. For example, the application may include an ASP.NET Core Web API project, several class libraries (for directly interfacing with databases via the Entity Framework) and an ASP.NET Core with React.js project. With a solution file, the dotnet CLI knows which projects to restore NuGet packages for ( dotnet restore ), build ( dotnet build ) and test ( dotnet test ) in your application. In this case, you will find a weather-api.sln file within the root of the project directory. Let's create a new ASP.NET Core Web API project: The dotnet new command scaffolds a new project or file based on a specified template , such as sln for a solution file and webapi for an ASP.NET Core Web API. The -n option tells the dotnet new command the name of the outputted project/file. In this case, you will find the ASP.NET Core Web API project located within an API directory. Let's add this project to the solution file: You can verify that the project has been added to the solution file by running the following command, which lists all of the projects added to the solution file: If you open the solution file, then you will find the "API" project listed with a project type GUID ( FAE04EC0-301F-11D3-BF4B-00C04F79EFBC for C#), a reference to the project's .csproj file and a unique project GUID. Let's restore the project's NuGet packages. For Node.js developers, this is similar to running npm install / yarn install on a freshly cloned Git repository to reinstall dependencies. If you are building this project on macOS, then you can find the NuGet packages in the ~/.nuget/packages directory. These packages relate to the package referenced in the API/API.csproj : Swashbuckle.AspNetCore . Swashbuckle.AspNetCore sets up Swagger for ASP.NET Core APIs. You can check the project's obj/project.nuget.cache file for absolute paths to the project's NuGet packages. Let's take a look at the three C# files in the API directory: Much like the index.js file of a simple Express.js RESTful API, the Program.cs file also bootstraps and starts up a RESTful API, but for ASP.NET Core. It follows a minimal hosting model that consolidates the Startup.cs and Program.cs files from previous ASP.NET versions into a single Program.cs file. Plus, the Program.cs file now makes use of top-level statements and implicit using directives to eliminate extra boilerplate code like the class with a Main method and using directives respectively. As you can see in the Program.cs file, setting up and running a RESTful API with ASP.NET Core requires significantly less code than previous ASP.NET versions. ( Program.cs ) Program.cs begins with instantiating a new WebApplicationBuilder , a builder for web applications and services. WebApplicationBuilder follows the builder pattern , which breaks down the construction of a complex object into multiple, distinct steps. This means that we delay the creation of the builder object ( var app = builder.Build() ) until we finish configuring it. Upon instantiation, the builder object comes with preconfigured defaults for several properties : Alongside these preconfigured defaults, we explicitly register additional services to the built-in DI ( d ependency i njection) container with WebApplicationBuilder.Services . This DI container simplifies dependency injection in ASP.NET Core (i.e., automatically resolves dependencies and manages their lifetimes) and is responsible for making all registered services available to the entire application. Here, the following methods get called on builder.Services : After registering these services, call the builder object's Build() method to build the WebApplication (host) with these configurations. By default, the WebApplication uses Kestrel as the web server. Then, we check if the application is running within a development environment, and if so, then add Swagger middleware ( UseSwagger() and UseSwaggerUI() ) to the application's middleware pipeline. Notice how these Use{Feature} extension methods that add middleware are prefixed with Use , which is similar to how Express.js calls app.use() to mount middleware functions. Calling the UseSwaggerUI() method automatically enables the static file middleware . Express.js also provides a built-in middleware function for serving static assets ( app.use(express.static("<path_to_static_files>")) ). The remaining middleware gets applied to all requests regardless of environment: After all of this middleware gets added to the middleware pipeline, we call the MapControllers() method to automatically create an endpoint for each of the application's controller actions and add them to the IEndpointRouteBuilder . This method saves us the trouble of having to explicitly define the routes ourselves. Lastly, we call the Run() method to run the application. So to start up the ASP.NET Core RESTful API, run the dotnet run command, which runs the project in the current directory, within the API directory. Note : If our application consisted of multiple projects, then you can specify which project you want to run by passing a --project option to dotnet run (e.g., dotnet run --project API to just run the API project) without having to change the current directory. When you run this command, you may come across the following error message: If you do, then follow the directions in the error message. Run the dotnet dev-certs https --clean command to remove all existing ASP.NET Core development certificates, and run the dotnet dev-certs https to create a new untrusted developer certificate. To trust this certificate, run the command dotnet dev-certs https --trust . Then, re-run the dotnet run command and the error message should no longer pop up. Alternatively, you can remove https://localhost:7101; from applicationUrl in the API/Properties/launchSettings.json file, which stores profiles that tell ASP.NET Core how to run a specific project. Within a browser, you can visit the Swagger documentation at http://localhost:5077/swagger . Here, you will find that the RESTful API comes with only a single endpoint: GET /WeatherForecast . If you expand the endpoint's accordion item, then a summary of the endpoint will appear: This summary provides an example response (status code, value, etc.) for the endpoint. If you test this endpoint by visiting http://localhost:5077/WeatherForecast in the browser, or sending a GET request to http://localhost:5077/WeatherForecast via a REST client like Postman or a CLI utility like cURL , then you will get a response that contains four weather forecasts. To see how the RESTful API handles requests to the GET /WeatherForecast endpoint, open the Controllers/WeatherForecastController.cs file. ( WeatherForecastController.cs ) If you have developed an Express.js RESTful API, then you should be familiar with the concept of controllers. After all, route callback functions act as controllers. To understand how this file works, let's first take a look at the [ApiController] attribute . This attribute tells ASP.NET Core that the controller class will opt-in to using opinionated, commonly-used API functionality like multipart/form-data request inference and automatic HTTP 400 responses . A route attribute ( [Route("[controller]")] ) is placed on the controller and coerces all controller actions to use attribute routing . The [controller] token in the route attribute expands to the controller's name, so the controller's base URL path is /{controller_name} , or in this case, /WeatherForecast . This means the URL path of /WeatherForecast can match the WeatherForecast.Get() action method. Since this action method is marked with the HttpGet attribute, only GET requests to /WeatherForecast will run this action method. When declaring it, a controller class in ASP.NET Core RESTful APIs should derive from the ControllerBase class, which provides the properties and methods needed for processing any HTTP request. This controller only contains one action method, WeatherForecast.Get() . This action method returns four weather forecasts. Each weather forecast is created with the WeatherForecast model that's defined in the API/WeatherForecast.cs file: ( WeatherForecast.cs ) This model represents the shape of a weather forecast's data. In the WeatherForecast.Get() action method, we pass several values to the model: And the model automatically populates each property accordingly. Proceed to the second part of this tutorial series to see how to add your own endpoints to this RESTful API.

Thumbnail Image of Tutorial Building Your First ASP.NET Core RESTful API for Node.js Developers - Introduction (Part 1)