Начало работы с asp.net core mvc: основные шаги

How Do ASP.NET Web APIs Work?

An ASP.NET Core Web API basically consists of one or more controller class that derives from ControllerBase. The ControllerBase class provides many methods and properties that are useful for working with HTTP requests.

As you can see in the image above, a “client” makes an “HTTP request” to the API, which—through the “controller”—identifies the call and makes the Read or Write in the “data access layer.” The “Model” is returned, in this case, a JSON object “Contact: Name” in the “HTTP response.” In simple terms, the API is bridging the “client” and the “data” in a simple and safe way.

Example console API response

Now that we’ve seen the basics of Web APIs, let’s create an API and see in practice how it works.

Getting a List of Items

Once you have the basic infrastructure for your controller, you need to add an action to it. An action is a public method of a controller mapped to an HTTP verb. So, add a new method to the class as shown in the following: :point_down:

The method allows the client to get the whole list of glossary items. It is decorated with the attribute which maps the method to HTTP GET requests sent to the URL path.

The return type of the method is . This means that the method will return a type object or an object deriving from . The type represents the HTTP status codes to be returned as a response. As said before, the class provides a few features to deal with HTTP requests. Some of these features are methods that create HTTP status code in a readable way, like , , , and so on. The value returned by the method represents the HTTP status code with the representation of the variable as the body of the response.

To test this first action implementation, run the application by typing the following command in a terminal window:

Then, navigate to https://localhost:5001/swagger with your browser. Now you should see your new endpoint as shown in the following picture:

By clicking the Get button and then the Try it out button that appears, you can test the new endpoint. You should see a screen like the following:

Here you can find some details about the endpoint. You know that it doesn’t require parameters. Also, you see that the only response it provides is a successful one (status code 200) with an array of JSON objects with the and string properties.

All you need to do at this point is to click on the Execute button and get the result, as shown below:

You get the command you should use to make the request with curl, the absolute URL of the Web API endpoint, and the actual Web API response. You see the glossary list implemented by the static variable and the headers sent by the server.

VII. Run and Test the Application

Now, It’s time to test our application. To see a sample display of a list of Authors on our View, use the code snippet below and replace the code on your HomeController.cs.

If you use an empty MVC template, ensure that the following libraries are installed.

  • Bootstrap 3.3.7
  • JQuery 1.10.2
  • Modernizr 2.6.2

If not, you can download it using NuGet Package Manager.

You may also visit this blog post to guide you on installing NuGet package.

Visit Blog Post

Now, you are ready to test your first ASP.NET web application.

1. Press F5 or click the “Run” button in Visual Studio to start the application.

2. Verify that your application launches in the browser, and you are able to see the list of dummy authors that we added on index action inside HomeController.cs.

3. You can also Use breakpoints and debugging tools to identify and resolve any issues.

If you follow along with this tutorial you should be able to see this on your browser.

If you observe, we have three hyperlink function on the view, “Edit”, “Details” and Delete. You can continue this project by creating their functionality, we only covered display list function on this tutorial.

Detailed ASP.NET MVC folder structure.

Visit Blog Post

4.1 ASP.NET Introduction

ASP.NET is a technology used for creating Web applications and Web services that are executed in the IIS server. The ASP.NET pages are compiled making the application faster that classic ASP. It provides good level of consistency over the web applications. It has a large set of user controls, XML based components and user authentication.

Framework of ASP.NET

                                                           Fig (a)

The ASP.NET framework is as shown in Fig (a). There various components of the ASP .NET framework and their features are mentioned below:

1. Common Language Runtime:

The Common Language Runtime (CLR) is used as execution engine for .NET framework. All the ASP.NET code is executed in the CLR. It performs functions like security, memory management, exception handling, thread execution, code verification, code security. The Just In time compiler is used for compilation of the ASP.NET code.

The source is compiled into the intermediate language code. The JIT compiler coverts the IL code into native code that is specific to the system.

2. Base Class Library:

The Base Class Library is the functionality available to all the .NET framework languages. It provides various features like database connectivity, XML document manipulation, classes and interfaces that are reusable with the CLR.

3. ADO.NET and XML:

ADO.NET is used for the database operations in .NET. It works efficiently with SQL Server, OLEDB, XML. The operations like accessing data from the data source, updating and manipulating data are performed through ADO.NET. Extensible Markup Language (XML) is useful for designing the web pages in .NET

4. Windows Forms:

The windows Forms application is used for creating window application in .NET. There are wide controls and designing features available for Windows Forms.

5. ASP.NET Web Forms and Services:

The Web Forms user to create Web based applications. They include web pages and several GUI components for designing. It helps simultaneous addition of controls at runtime and design time.

Web Services are used when the user needs specific task to be executed. They are used for creating single application or distributed on the web.

6. Common Language Specification:

The Common Language Specification (CLS) is a set of language features used for developing web application and web services. It ensures interoperability among applications without the language dependency. It defines  a subset of Common Type System (CTS) providing objects of different languages to interact with each other.

7. Visual Studio .NET:

The Visual Studio .NET is used for developing all the web and windows applications. The GUI interface and extensive built in class libraries are provided in the component. Web Services can be developed and deployed using Visual Studio.

Advantages of ASP.NET

  • The code is reduced for building application through ASP.NET
  • It is server side technology, the code is executed at the server before sending it to the browser.
  • It is easy to deploy applications as the components are not registered in the system
  • The applications developed are safe and secure due to Windows authentication
  • The performance is better due to early binding, just in time compilation, and code optimization
  • It is language independent providing user the flexibility to develop the application
  • The ADO.NET used for data binding makes the application run faster with large volume of data

Преимущества ASP.NET

Производительность. Код приложения или страницы, созданных с помощью этой платформы, компилируется по необходимости. Кроме того, компиляция осуществляется только один раз, а машинный код сохраняется в системные папки. В совокупности это существенно повышает производительность платформы, особенно по сравнению с аналогами, доступными на момент выпуска первой версии.

Минимизация ошибок. Большинство ошибок в исходном коде «отлавливается» платформой еще на стадии разработки. Однако, даже если какие-то баги будут пропущены системой в готовый код, они обрабатываются непосредственно при выполнении запущенной программы. Это, с одной стороны, упрощает процесс разработки, так как программисту не приходится искать ошибки вручную. С другой — повышает стабильность работы приложения за счет устранения критических багов.

Мультиязычность. Приложения в ASP.NET можно писать на большинстве современных распространенных языков программирования, так как все они поддерживаются «материнской» платформой .NET Framework. Исходный код программы преобразуется в промежуточный, который уже затем компилируется в машинный код. Благодаря поддержке множества языков программирования ASP.NET становится действительно универсальной платформой, доступной для использования программистами, изучающими разные языки программирования. 

Привязка к Windows. Хотя ASP.NET разрабатывается и поддерживается Microsoft, является собственностью этой корпорации, она доступна для использования на ПК с операционными системами MacOS и Linux. Это существенно расширяет число программистов, которые могут использовать эту платформу для создания веб-приложений. 

Использование повторяющегося кода. Благодаря таким функциям, как повторно применяемые классы и шаблоны, программисту не обязательно переписывать код повторяющихся элементов веб-приложения. С одной стороны, это делает разработку более быстрой и удобной, с другой — снижает вероятность появления ошибок (достаточно один раз отладить повторяющийся элемент).

Простота разработки. ASP.NET создана в рамках основного подхода Microsoft к программированию как к максимально простому процессу, многие функции и стадии которого можно автоматизировать. Широкий набор элементов управления, инкапсулируемые объекты, преобразующиеся в HTML-разметку, шаблоны и другие возможности значительно упрощают создание веб-приложений, в том числе комплексных. Наличие в ASP.NET нескольких платформ позволяет программисту выбрать инструменты, соответствующие его уровню знаний и навыков.

Многофункциональность. ASP.NET обладает широким набором различных функций, компонентов, элементов управления, шаблонов страниц и т.д. Благодаря этому с помощью фреймворка можно разрабатывать сайты и веб-приложения различного размера и структуры, придавать им уникальный облик, тестировать готовые продукты и выполнять подавляющее большинство операций, связанных с разработкой. Кроме того, функционал платформы можно расширить путем установки дополнительных расширений и интеграции с .NET.Framework.

4.4 Event Handler Properties

The Event Handler are used for handling the action performed by the control in the application. Every control is associated with an event. The functionality to be performed is added in the event handler in the code behind file.

User can create event handler through Properties window and code editor of the ASP.NET application.

1) Create an event handler through the Properties window.

Navigate to the design view of the application. Select the control for which you want to create an event handler. In the ‘Properties’ window, select the events symbol which is visible as shown.

Navigate to the event name property of the respective control. The control will be named as controlID_event.  Insert the name of the handler for the control. In the drop down list, select the name of the event handler, the list of methods with their signature for the event will be displayed. When the process is completed, user can switch to the editor and insert code in the event handler.

2) Create an event handler through code editor.

If the code editor is a single file web page, user can switch to the Source View to add the event handler.

If there is a code behind page, navigate to the Solution Explorer. Right click for the specific page and click ‘View Code’. Select the control from the drop down list and click on the event associated with the control. The event handler will be added for the control.

Consider an example to create a handler for page events. In the code editor create Page_event method. The page will automatically bind page events to the methods present in the code. The AutoEventWireup attribute in the @Page directive is set to true. As a result the page binding is automatic. The example of the page_event handler is shown below:

Consider an example for adding the handler to the control. The method name can be selected by the user. In the markup of the control, the event handler name is written as On<event name>. Consider a Button Control which has OnClick event bounded for it.

The source code of the Button Control is shown below:

The code behind file containing the event handler is shown as follows:

The output when the code is executed on the server will display the text present in the Textbox.

Работа и зарплата

Вакансий много как на должности разработчика PHP, так и ASP.Net. В среднем, зарплата у ASP.Net-специалиста немного выше, но это отнюдь не значит, что нельзя найти очень хорошо оплачиваемую работу PHP-программисту – все зависит от уровня профессионализма.

Вакансии программистов на PHP, в основном, открывают веб-студии, занимающиеся созданием сайтов. ASP.Net-разработчики чаще всего требуются в крупных компаниях, занимающихся корпоративными приложениями.

Среди фрилансеров (людей, работающих удаленно) гораздо большее распространение получил PHP – в основном, в силу легкости изучения. Однако, в этой ситуации программист на ASP.Net имеет некоторое преимущество: создав сайт заказчику на этой платформе, он получает высокие шансы повторного обращения (например, с целью добавления функциональности на сайт) именно к нему – найти другого фрилансера, работающего с этой платформой, довольно тяжело.

A sneak peek at the performance benchmarks of ASP.NET Core

The performance of ASP.NET Core WebAPI is blazing fast. As per the techempower benchmarks, ASP.NET Core stood next to pico.v in terms of .

Best plaintext responses per second, Dell R440 Xeon Gold + 10 GbE – TutLinks

In the category of web frameworks that perform at least a single query to database, the  show that ASP.NET Core has got its major share in the list of Best performance web frameworks.Best database-access responses per second, single query, Dell R440 Xeon Gold + 10 GbE – TutLinks

If you are looking to build a high-performance web application for next billion users, ASP.NET Core for .NET 6 is the go-to web framework of your choice.

Both the aforementioned benchmarks were obtained from techempower website. According to the source, these benchmarks were taken for a web application written using ASP.NET Core running on Kestrel web server on Linux. The physical hardware used to benchmark performance is Dell R440 Xeon Gold + 10 GbE.

Introduction

ASP.NET is an open-source web framework created by Microsoft. It is used to build modern web apps and services with .NET. ASP.NET is cross-platform and runs on Windows, Linux, macOS, and Docker. It is mainly used to design dynamic web pages and web applications and services. ASP.NET is a server-side web development model. 

The first version of ASP.NET was released in January 2002 and was based on Windows Programming. Various versions of ASP.NET have been released so far. They are as follows:

  • Version 1.0 was released in January 2002 with the release of Visual Studio .NET
  • Version 1.1 was released in April  2003 with Visual Studio .NET 2003 and Windows Server 2003
  • Version 2.0 was released in November 2005 with Visual Studio 2005 and SQL Server 2005.
  • Version 3.0 was released in November 2006
  • Version 3.5 was released in November 2007 with the release of Visual Studio 2008 and Windows Server 2008 and later Version 3.5 Service Pack 1 was released in August 2008
  • Version 4.0 was released in April 2010
  • Version 4.5 was released in August 2012 with Visual Studio 2012 and Windows Server 2012

ASP.NET offers 3 frameworks for creating web applications. These frameworks are

Confused about your next job?

In 4 simple steps you can find your personalised career roadmap in Software development for FREE

  1. ASP.NET Web Forms
  2. ASP.NET MVC
  3. ASP.NET web pages

All the 3 frameworks are quite stable and mature to create great web applications.

The Visual Studio 2022 Update

Historically, the .NET Framework has only worked on Windows devices. And Visual Studio played a big part of that. Up until now, Microsoft’s complete attention was devoted to maintaining, growing and developing the .NET Framework.

As of recently, the company has been pushing hard with its cross-platform, open source vision of software development, promoting the .NET Core and ASP.NET Core frameworks. And that vision is reflected in their latest Visual Studio 2022 update.

Once the IDE is installed, there is no more option for you to create ASP.NET MVC5 Web Project in Visual Studio 2022. So, the question still lingers. What can we do about it? How can we create a new ASP.NET MVC5 Web Project?

How to Create ASP.NET MVC Application

To Create ASP.NET MVC Application you need to follow these steps

  1. Open Visual Studio and Create empty MVC application.
  2. Add Controller
  3. Return “Hello World” from the Controller.

We are also going to analyse the code and explain how it works.

Create a Project


Create ASP.NET MVC Application

  1. Open Visual Studio.
  2. File -> New Project.
  3. Choose Visual C#.
  4. Select Web.
  5. Select ASP.NET Web Application.
  6. Name the Project as MvcHelloWorld.
  7. Click on OK. This will take you to New ASP.NET Project window.


New ASP.NET Project

  1. Select Empty. You can choose MVC Option here, which will create the MVC Project with the predefined template.  For this example, let us choose the Empty template.
  2. Select MVC.
  3. Click OK. This will create the new project MVCHelloWorld.

MVC Project Folders


Solution Explorer MVC Application

You can see from the above that ASP.NET MVC has created several project folders under the project MVCHelloWorld.  Here is the brief explanation of each folder.

App_Data is where the application data is stored.

Content is where files such as cascading style sheet files, images, icons are stored.  Content folder is not created in our project as we had opted for an empty project.

App_start is the location for configuration files of the MVC applications. In our project, you can see RouteConfig.cs.

Scripts are the location for javascript files that application needs.  This folder is not created as we have chosen empty project.

Controllers folder is the location for MVC controllers.  Controllers are responsible for user actions.  It is required of the MVC that the names of all controllers must end with the word “Controller”. For Example HomeController, UserController etc.

Models is the location for the model classes which will represent applications data

Views is the location for MVC views.

Add Controller

In ASP.NET MVC function of Controller is to react to the user input and present the appropriate page (View in MVC) to the user.  Let us now create a Controller.


Add New ASP.NET MVC Controller

  1. Select Controller Folder.
  2. Right Click
  3. Click on Add -> Controller This will take you to the Add Scaffold Dialog box
  4. From the available templates Select MVC 5 Controller Empty.
  5. Click on Add. This will open Add Controller dialog box.
  6. Name the controller as HomeController. Note that the Controller name ends with Controller. This is the Convention followed by the ASP.NET MVC to identify controllers.
  7. Click on Add.
  8. HomeController is added to our application.

HomeController

The following code is automatically added to the HomeController by the visual studio.

1
2
3
4
5
6
7
8
9
10
11

publicclassHomeControllerController

{
// GET: Home

publicActionResult Index()

{

returnView();

}
}
 

Let us look at the code closely.

1
2
3

publicclassHomeControllerController

 

HomeController class is inherited from the Controller class. This class resides in System.Web.MVC Namespace. All Controllers in ASP.NET MVC must inherit from Controller Class

1
2
3
4
5
6
7
8

publicActionResult Index()

{

returnView();

}
 
 

What is a Action Method

The Public methods which are added to the Controller are called Action Methods, meaning that you can perform some actions by invoking these Methods. In the above code Index is an Action Method, which returns ActionResult.

What is a ActionResult

The return type of a  Action Method (Controller method) is called ActionResult. In the above code Index method is called Action Method. The Return type of index method is called ActionResult. In the above code Index method returns View

We are yet do define any Views in our Project. If you run the above code you will see an error message (Resource not found).

Hello world

Now let us change Index method returns a “Hello, World”. Replace the Index method with the following

1
2
3
4
5
6
7

publicstringIndex()

{

return»Hello, World»;

}
 
 

Run the Project and you should be seeing “Hello, world” in your browser.


Hello World

  1. When we ran our web application we initiated the request for the root page
  2. The request was passed to HomeController. How did our application know the request was to be passed to HomeController?. That is because MVC Application sets up HomeController as the default controller. If nothing is specified in our url,  then the request is passed to the HomeController.
  3. HomeController calls its action method Index Again, here we have not specified any action method in our url.  Our application picked up Index action method because the index is setup as the default action method.
  4. Index action method returns “Hello World” to the browser
  5. browse displays the “Hello World”

Create ASP.NET MVC5 Web Project in Visual Studio 2022: Solution

Start by running Visual Studio 2022. You should get the following window

Visual Studio 2022 Start a New Project

This should be quite familiar, since this window is no different than its Visual Studio 2019 predecessor. Click on Create a new project option. As a result Visual Studio 2022 will open another window.

On the Create a new project page, make sure to select C# as the language of choice. Then set the platform to Windows and select Web as the project type. Visual Studio 2022 will then list the start-up project templates.

Now, try to find the following template: ASP.NET Web Application (.NET Framework). Most probably you won’t be able to. Visual Studio forces you to use the .NET Core framework for your web project by default.

You can also try and search for the template. Please feel free to start typing the name of the template, but the search will yield no familiar results.

Visual Studio 2022 – Create a New Project

The Project Structure

Now, let’s examine the project structure and look at the files generated as part of the default MVC template:

We can see that the project is well organized into separate folders for , , and . The Views are further organized into subfolders corresponding to each view. There are some default files generated in each of these folders as well. Then there are the usual configuration and startup files that come with the .NET Core project template.

Now let’s run the app with . We can see a website based on the default layout provided by ASP.NET Core MVC:

Congrats! We have just created a website using ASP.NET Core MVC.

Register the repository¶

By defining a repository interface, we can decouple the repository class from the MVC controller that uses it. Instead of instantiating a inside the controller we will inject an using the built-in support in ASP.NET Core for dependency injection.

This approach makes it easier to unit test your controllers. Unit tests should inject a mock or stub version of . That way, the test narrowly targets the controller logic and not the data access layer.

In order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs file. Add the following using directive:

using TodoApi.Models;

In the method, add the highlighted code:

Getting a Single Item

The next action you are going to create will allow your client to get a single glossary item. The action will expect a term as input and will provide an instance of as a result.

Add a new method definition to the controller class after the previous action definition, as in the following:

As you can see, you have an overloaded definition of the method mapped again to the HTTP GET verb. However, in this case, you have a attribute for the action. This attribute appends a new variable element to the URL of the action. So, this action will respond to the HTTP request sent to the URL pattern . The part of the pattern can be replaced by any non-empty string and its value will be mapped to the parameter.

This method checks if the requested term exists in the list and returns the glossary item. If the term doesn’t exist, it returns a HTTP status code.

Now, restart the application and test this new action by navigating to https://localhost:5001/swagger.

This time, you have two endpoints on the page, as you can see in the following picture:

In this case, you have a mandatory parameter to provide before testing the endpoint. Try to insert the JWT value and you should get the definition of the JWT term as a response.

Interested in getting up-to-speed with JWTs as soon as possible?

Download the free ebook

Понравилась статья? Поделиться с друзьями: