banner



How To Find Mvc Version In Visual Studio

Your first app using ASP.NET Cadre 6 and Visual Studio 2022

If you are keeping an eye on the progress of ASP.Net Cadre 6 you lot are probably enlightened that .Internet 6, C# 10, and Visual Studio 2022 take been released. There are lots of new things, small to big, added to the overall .Net family unit and I take discussed a few of them in my previous manufactures. In this article I volition show yous how to create your first web application in Visual Studio 2022. I presume that yous are already familiar with Visual Studio 2019 and ASP.Internet Core in general. This is going to be a quick introduction to requite y'all a feel of the new IDE and projection construction.

Before you lot go any farther, install Visual Studio 2022 edition of your choice.

So, let's become going!

Open Visual Studio 2022 as shown below.

This dialog should look familiar to you because information technology'south quite similar to Visual Studio 2019.

Click on the Create a new project option to reveal the project templates.

Hither you can see a list of all bachelor project templates. I accept filtered them for C# linguistic communication and Web project blazon. As far equally ASP.NET Core is concerned the master project templates that you discover listed hither include:

  • ASP.Cyberspace Cadre Web App (Razor Pages)
  • ASP.NET Core Web App (Model-View-Controller)
  • ASP.Internet Core Empty
  • Blazor Server App
  • Blazor WebAssembly App
  • ASP.Internet Core Spider web API (past default uses controller based API but can exist changed to Minimal API during project cosmos)
  • ASP.Cyberspace Core gRPC Service
  • Razor Course Library

For this instance nosotros will deliberately use ASP.NET Core Empty project template so that nosotros can setup everything on our own rather than relying on the default projection items.

So, pick ASP.Internet Core Empty and hit the Next button.

Specify some project proper name (FirstAppInAspNetCore6 in this case) and location and click on the Adjacent push.

In this dialog you can select a .NET version. When you install Visual Studio 2022, .Net 6 is automatically installed for yous and hence this dropdown currently has merely that entry. The Configure for HTTP checkbox is checked indicating that you want to use Visual Studio'south evolution SSL certificate while developing the project.

Click on the Create push to stop the projection creation wizaed and to create the projection as per our specifications. The following figure shows how the Solution Explorer looks similar with the Empty projection loaded.

Notice that there is no Startup.cs file because VS2022 project templates use the new hosting APIs for the projects. Previously you rarely tampered with Projection.cs file. But now Program.cs has a lot more than responsibility as you volition see shortly.

Double click on the project name in Solution Explorer to open its .csproj file in the editor.

<Project Sdk="Microsoft.Net.Sdk.Spider web">    <PropertyGroup>     <TargetFramework>net6.0</TargetFramework>     <Nullable>enable</Nullable>     <ImplicitUsings>enable</ImplicitUsings>   </PropertyGroup>  </Project>

Every bit you can see the projection's SDK is Microsoft.NET.Sdk.Web. The target framework is gear up to net6.0 indicating that we are using .Cyberspace vi. Notice the Nullable and ImplicitUsings elements.

The <Nullable> chemical element decides the project wide behavior of Nullable reference types. The value of enable indicates that the Nullable reference types are enable for the projection.

The <ImplicitUsings> chemical element can exist used to enable or disable what is known every bit Implicit Usings for the project. When <ImplicitUsings> is set to enable, sure mutual namespaces are implicitly imported for you. Y'all can read more most this characteristic here.

You can also take a await at these project settings (and change them if required) using the project's properties page. To open up the project's holding page right click on the project in Solution Explorer and click on Properties shortcut carte option. The following figure shows a part of this properties page.

Y'all can also search for a particular projection setting such equally target framework, nullable, or implicit usings this folio every bit shown below:

For this example we won't change whatsoever of these settings. Then, let them be at their default values and proceed to the next step.

Now add together Models, Views, and Controllers folders equally usual. And also add a model class named MyModel to the Models folder.

The default MyModel class contains the following code:

namespace FirstAppInAspNetCore6.Models {     public class MyModel     {     } }

Permit'due south change this lawmaking to use file scoped namespaces.

          namespace FirstAppInAspNetCore6.Models;                    public grade MyModel {     public string Message { get; set up; } }

Equally you can see the namespace line now has a semicolon at the end and doesn't wrap the form inside curly brackets. This indicates that the whole content of the file that follows is part of the FirstAppInAspNetCore6.Models namespace. Thus, MyModel class will be a role of FirstAppInAspNetCore6.Models namespace. As well notation that we take added Message string property to the MyModels class.

You lot will discover that the Bulletin holding shows a dark-green underline and displays this warning message:

Open the .csproj file over again and change the value of <Nullable> element to disable.

<TargetFramework>net6.0</TargetFramework>          <Nullable>disable</Nullable>          <ImplicitUsings>enable</ImplicitUsings>

You will find that the warning disappears. We did this just to cheque the issue of <Nullable> projection settings on the lawmaking. Modify the <Nullable> setting back to enable.

Let'southward too check the consequence of <ImplicitUsings> element. Change its value to disable and effort building the application.

<TargetFramework>net6.0</TargetFramework> <Nullable>enable</Nullable>          <ImplicitUsings>disable</ImplicitUsings        

You will get this mistake bulletin in Plan.cs file.

Why did this error occur? That's because the WebApplication class resides in the Microsoft.AspNetCore.Architect namespace. When <ImplicitUsings> was enable, this namespace got automatically imported for u.s.. When we disabled implicit usings, the Microsoft.AspNetCore.Builder namespace was no longer automatically imported for the states and the compiler generated the error.

Change <ImplictUsings> dorsum to enable and build the awarding once again. This fourth dimension the fault volition disappear and the app will build successfully.

Now add HomeController class to the Controllers folder using Add together New Detail dialog.

The default HomeController course looks similar this:

using Microsoft.AspNetCore.Mvc;  namespace FirstAppInAspNetCore6.Controllers {     public class HomeController : Controller     {         public IActionResult Index()         {             return View();         }     } }

This code should expect familiar to you. We will change this lawmaking to the following:

          global using Microsoft.AspNetCore.Mvc;                    namespace FirstAppInAspNetCore6.Controllers;                    public class HomeController : Controller {     public IActionResult Alphabetize()     {         return View();     } }

Notice the code marked in bold messages.

The using statement at the top now has global keyword added to it. This will automatically import the concerned namespace in all the C# classes. For example, if you have three controller classes then you no longer need to use Microsoft.AspNetCore.Mvc in all of them. Just one "global" using volition make it available for all C# classes. You can separate all the global using directives in a dissever .cs file. For case, you lot can place the above global using inside a file named GlobalUsings.cs. This fashion you can manage all the global usings at one place (for this example you volition need to import FirstAppInAspNetCore6.Models and Microsoft.AspNetCore.Mvc). The following figure shows such a file in a sample project.

The HomeController.cs besides uses file scoped namespace - FirstAppInAspNetCore6.Controllers - as discussed before.

Now modify the Index() action every bit shown below:

public class HomeController : Controller {     public IActionResult Index()     {         MyModel model = new MyModel()         {             Message = "Hullo World!"         };         return View(model);     } }

This code is quite straightforward. We unproblematic create an object of MyModel, ready its Message property, and laissez passer information technology to the Index view.

Next, add the Index view using Add New Item dialog.

Write this markup and code in Index.cshtml:

@model FirstAppInAspNetCore6.Models.MyModel  <h1>@Model.Message</h1>        

We haven't added _ViewImports file in the project and hence we need to specify the fully qualified proper noun of the model class in the @model directive.

Before nosotros run the application we need to configure the application's startup.

Open Program.cs and add together the following code to it:

var builder = WebApplication.CreateBuilder(args);  builder.Services.AddControllersWithViews();  var app = builder.Build();  app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting();  app.MapGet("/hi", () => {     return new List<string>() {         "Hello Globe!",         "Hi Galaxy!",         "Hullo Universe!"     }; });  app.MapDefaultControllerRoute();  app.Run();

Previously we used two separate files namely Program.cs and Startup.cs to configure app hosting and startup. Now, that chore happens in Program.cs itself. The new hosting APIs and new routing APIs along with C# top level statements simplify this process to a large extent.

First, we create a WebApplicationBuilder using the CreateBuilder() method. And so we register MVC specific services with DI container using the AddControllersWithViews() method.

Once a WebApplication instance is built with the help of Build() method nosotros wire a series of middlewares to the HTTP pipeline. This is washed using a series of UseXXXXXXX() methods.

Finally, we configure the routing endpoints. The MapGet() method configures a minimal API endpoint at /hi and MapDefaultControllerRoute() takes of the default MVC routing - /controller/action. The MapGet() handler delegate simply returns a Listing of string messages to the caller. Nosotros volition invoke this minimal API endpoint from the browser.

The Run() method starts the web application.

Now that our app startup is washed, we are ready to run the application. Click on the Start Debugging icon from the Visual Studio toolbar or press F5. Yous volition notice that Visual Studio 2022 uses Kestrel web server past default rather than IIS Express. Of form, you can switch them from the toolbar menu.

Visual Studio 2022 may prompt y'all nearly the evolution SSL certificate. If all goes well you will see "Hello World!" in the browser every bit shown below:

Notice that the Kestrel web server now uses a randomly generated port numbers instead of fixed 5000 and 5001. You can configure them in launchSettings.json file under Backdrop binder.

"FirstAppInAspNetCore6": {     "commandName": "Project",     "dotnetRunMessages": true,     "launchBrowser": true,                      "applicationUrl": "https://localhost:7286;                        http://localhost:5286",                    "environmentVariables": {     "ASPNETCORE_ENVIRONMENT": "Development"     } }

Now, become to the browser's accost bar and navigate to /hello to check whether the minimal API endpoint works as expected. Here is the issue:

As y'all can come across, we get a JSON array with the 3 string letters.

Allow'southward conclude this exploration by checking Hot Reload in activity.

Run the application as before so that "Hello World!" is displayed in the browser.

When you run the app, Visual Studio hot reload button menu will exist enabled for you like this:

Hot reload allows you to make changes to the HTML, CSS, and C# code and utilise them to the app running in the browser, all without stopping and restarting the app.

To test the bones usage of hot reload, get to the Alphabetize() activity and change the message from "Howdy World!" to "Hello Universe!" (don't stop the app, information technology should exist running in the browser).

public IActionResult Alphabetize() {     MyModel model = new MyModel()     {         Message = "Hello Universe!"     };     render View(model); }

Likewise open the Index.cshtml and change <h1> to <h3>.

<h3>@Model.Message</h3>

Salve both the files, click on the Hot Reload buton (see above effigy), and refresh the browser window. You will see the changed message and markup as shown beneath:

Yous can further simplify the process of applying the changes by selecting the "Hot Reload on File Relieve" option. This will perform hot reload equally before long every bit yous save the changes (you lot won't need to explicitly click on the Hot Reload button).

To summarize, we touched upon several improvements in ASP.Internet Core vi projects and Visual Studio 2022 including <Nullable>, <ImplicitUsings>, global usings, file scoped namespaces, new manner of app startup, minimal API, and hot reload.

That'south it for now! Go on coding!!

Source: http://www.binaryintellect.net/articles/c131fc47-0c9d-496b-998a-ed65a2486896.aspx

Posted by: alfordtheyetage.blogspot.com

0 Response to "How To Find Mvc Version In Visual Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel