European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Swagger For .NET MVC Web API

clock July 8, 2022 09:38 by author Peter

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification. Swagger UI is an alternative to Postman.


I used Swagger more than several times in my articles, but just as a minor tool associated with different other major topics. When I tried to get info on Swagger, I had to search from these articles, which were not convenient. So, I rewrote these two articles, especially about Swagger for .NET MVC Web API or .NET Core MVC Web API.

This article is part of another article: Exception Handling (2), In ASP.NET MVC Web API, we got Swagger related part here. You can see details from there.
Step 1 - Create an ASP.NET MVC Web API app

We use the version of Visual Studio 2019 16.8 and .NET Framework 4.7.2 to build the app.

    Start Visual Studio and select Create a new project.
    In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
    In the Configure your new project dialog, enter ErrorHandlingWebAPI for Project name > Create.
    In the Create a new ASP.NET Web Application dialog, select Web API > Creat

Build and run the app, you will see the following image shows the app,

Step 2 - Add one empty ApiController
Add one empty apiController into the app, with the name as ErrorHandlingWebAPIController:
    Right click Controllers > add > controller.
    In the Add New Scaffolded Item dialog, select Web API in the left pane, and
    Web API 2 Controller - Empty > Add.
    In the Add Controller dialog, Change ErrorHandlingWebAPIController for controller name > Add.

Step 3 - Add code into the controller
We add the following code into the controller,
[Route("CheckId/{id}")]
[HttpGet]
public IHttpActionResult CheckId(int id)
{
    if (id < 10) // No error hanbdling at all:
    {
        int a = 1;
        int b = 0;
        int c = 0;
        c = a / b; //it would cause exception.
    }
    else if (id <20) // Error handling by HttpResponseException with HttpStatusCode
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }
    else if (id < 30) // Error handling by HttpResponseException with HttpResponseMessage
    {
        var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent(string.Format("No Employee found with ID = {0}", 10)),
            ReasonPhrase = "Employee Not Found"
        };

        throw new HttpResponseException(response);
    }

    return Ok(id);
}


Step 4 - Add Swagger Client
Installing Swagger from NuGet Package Manager, from Visual Studio project,

    Right click Tools > NuGet Package Manager > Manage NuGet for Solution
    In the opened NuGet-Solution dialog: Click Browse, then Search Swagger
    Install Swashbuckle v5.6.0

Before installation of Swagger, MVC usually has four config files in folder App_Start,


 

After installation, one more file, SwaggerConfig.cs, added,

with code,
public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;
        GlobalConfiguration.Configuration
          .EnableSwagger(c => c.SingleApiVersion("v1", "ErrorHandlingWebAPI"))
          .EnableSwaggerUi();
    }
}


Step 5 - Change the default start page to the swagger

Right click Project > Properties to open the properties page, then choose Web, in Start URL, add /swagger,


Step 6 - Run the app




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Consume Web API By MVC In .NET Core, Server And Framework

clock June 28, 2022 08:54 by author Peter
Microservice is a modern software development architecture: loosely-coupled architecture with application scope.  It basically includes two parts: Client and API. Theoretically, API is a server, it could be built by any language or any platform or any device. The client is the consumer of the API Server that, in turn, could be applications of a smartphone, tablet, Windows, Mac, or any kind of browser, and could be built by any platfom and language.

 
ASP.NET Web API is, specifically, a Microsoft product to produce the RESTful output through HTTP for Clients. The consumer of ASP.NET Web API could be:
  • Javascript client,
  • Angular client,
  • Node.js client,
  • jQuery client,
  • C# code such as Console, MVC, WebForm, Windows, and so on.
In this article, we will consider the C# client, and specifically an ASP.NET MVC client in .NET Core. If we Google it, we can find out a lot articles that describe the C# client to consume Web API (see some of the references at the end of this article). However, most of them seem quite complex, and even you could follow the steps to build a project, it is hard to follow the points to re-do one for yourself.

The contribution of this article is that I will try to make one-line code to build the MVC Client. Before the one-line code, we will use all of the knowledge and techniques we are familiar with to build the server and client framework.

This article will be divided in two parts, Part I (this article) will create a ASP.NET Core Web API (server), and also a ASP.NET Core MVC module (Client base). The later one will be used as a framework of the one-line code MVC Client. Part II will implement the one-line code Web API Client to be a Web API consumer.

A: Build ASP.NET MVC in .NET Core with Entity Framework Database First

This part will create a ASP.NET Core MVC application with Entity Framework Database first approach.

  • Step 1: Create an ASP.NET Core MVC application
  • Step 2: Reverse engineer Entity model from database (database first aproach for entity)
  • Step 3: Scaffold Controller with View using Entity Framework
  • Step 4: Run and Test app
At the end, you have an MVC app that can consume a database directly through entity framework.

Step 1: Create an ASP.NET Core MVC application

We use the current version of Visual Studio 2019 16.8 and .NET 5.0 SDK to build the app.

  1. Start Visual Studio and select Create a new project.
  2. In the Create a new project dialog, select ASP.NET Core Web Application > Next.
  3. In the Configure your new project dialog, enter MVCCallWebAPI for Project name.
  4. Select Create.
  5. In the Create a new ASP.NET Core web application dialog, select,
     
    1. .NET Core and ASP.NET Core 5.0 in the dropdowns.
    2. ASP.NET Core Web App (Model-View-Controller).
    3. Create

Build and run the app, you will see the following image shows the app,

Step 2: Reverse engineer Entity model from database (database first aproach for Entity)
We use a local Microsft SQL server, and the sample database pubs and its table stores as our database sample. We try to reverse engineer to get the table Stores into the project and make an entity model Store.
 
Click "Tools->NuGet Package Manager->Package Manager Console" as shown below i.e.


This is the reverse engineering command (when you run the command in PMC, you need to make it in one line),
    Scaffold-DbContext "Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer   
    -OutputDir Models/DB   
    -Table dbo.stores  


Run the command in the PMC,

We got error message above that Microsoft.EntityFrameworkCore.Design is required, but not installed. Click "Tools->NuGet Package Manager->Manage NuGet Packages for Solution" as shown below,

Choose and install: Microsoft.EntityFrameworkCore.Design,

Run the PMC command again,

We got: Unable to find provider assembly 'Microsoft.EntityFrameworkCore.SqlServer', install it in the same way above from Manage NuGet Packages for Solution, and then reRun PMC command. This was successful and two classes are reverse engineered under Models/DB as shown below: pubsContext.cs and Store.cs

Step 3: Add Controller with View using Entity Framework
For adding controller using entity framework, we need to modify the reverse engineered classes pubsContext and Store.cs.
1. Modify the data connection
For the class pubsContext, we need to comment out the data connection part,

    //        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    //        {  
    //            if (!optionsBuilder.IsConfigured)  
    //            {  
    //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.  
    //                optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");  
    //            }  
    //        }  

and move the data connection string into file appsettings.json,
     {        
      "Logging": {        
        "LogLevel": {        
          "Default": "Information",        
          "Microsoft": "Warning",        
          "Microsoft.Hosting.Lifetime": "Information"        
        }        
      },        
            
      "ConnectionStrings": {        
        "DevConnection": "Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"        
      },        
          
      "AllowedHosts": "*"        
    }    


Register the database connection context into Class starup.cs inside ConfigureServices,
    public void ConfigureServices(IServiceCollection services)        
    {        
        // Register SQL database configuration context as services.         
        services.AddDbContext<pubsContext>(options =>        
        {        
            options.UseSqlServer(Configuration.GetConnectionString("DevConnection"));        
        });        
            
        services.AddControllersWithViews();        
    }    


Otherwise,  we could make a controller with view using this entity framework, and this would not work.
 
2. Modify the model
In class pubsContext, we can also comment out the data constrain part,
    //protected override void OnModelCreating(ModelBuilder modelBuilder)    
    //{    
    //    modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");    
        
    //    modelBuilder.Entity<Store>(entity =>    
    //    {    
    //        entity.HasKey(e => e.StorId)    
    //            .HasName("UPK_storeid");    
        
    //        entity.ToTable("stores");    
        
    //        entity.Property(e => e.StorId)    
    //            .HasMaxLength(4)    
    //            .IsUnicode(false)    
    //            .HasColumnName("stor_id")    
    //            .IsFixedLength(true);    
        
    //        entity.Property(e => e.City)    
    //            .HasMaxLength(20)    
    //            .IsUnicode(false)    
    //            .HasColumnName("city");    
        
    //        entity.Property(e => e.State)    
    //            .HasMaxLength(2)    
    //            .IsUnicode(false)    
    //            .HasColumnName("state")    
    //            .IsFixedLength(true);    
        
    //        entity.Property(e => e.StorAddress)    
    //            .HasMaxLength(40)    
    //            .IsUnicode(false)    
    //            .HasColumnName("stor_address");    
        
    //        entity.Property(e => e.StorName)    
    //            .HasMaxLength(40)    
    //            .IsUnicode(false)    
    //            .HasColumnName("stor_name");    
        
    //        entity.Property(e => e.Zip)    
    //            .HasMaxLength(5)    
    //            .IsUnicode(false)    
    //            .HasColumnName("zip")    
    //            .IsFixedLength(true);    
    //    });    
        
    //    OnModelCreatingPartial(modelBuilder);    
    //}    
        
    //partial void OnModelCreatingPartial(ModelBuilder modelBuilder);    


but, we need to modify the data model to make the table member names exactly the same as they are in database, such as StorId into Stor_Id, and add a  [Key] for primary key in database.
 
The class Store.cs, before,
    using System.ComponentModel.DataAnnotations;    
      
    #nullable disable    
        
    namespace MVCCallWebAPI.Models.DB    
    {    
        public partial class Store    
        {    
            public string StorId { get; set; }    
            public string StorName { get; set; }    
            public string StorAddress { get; set; }    
            public string City { get; set; }    
            public string State { get; set; }    
            public string Zip { get; set; }    
        }    
    }     


After
    using System.ComponentModel.DataAnnotations;    
      
    #nullable disable    
        
    namespace MVCCallWebAPI.Models.DB    
    {    
        public partial class Store    
        {    
            [Key]    
            public string Stor_Id { get; set; }    
            public string Stor_Name { get; set; }    
            public string Stor_Address { get; set; }    
            public string City { get; set; }    
            public string State { get; set; }    
            public string Zip { get; set; }    
        }    
    }    

The final class pubsContext will be,
    using Microsoft.EntityFrameworkCore;  
     
    #nullable disable  
      
    namespace MVCCallWebAPI.Models.DB  
    {  
        public partial class pubsContext : DbContext  
        {  
            public pubsContext()  
            {  
            }  
      
            public pubsContext(DbContextOptions<pubsContext> options)  
                : base(options)  
            {  
            }  
      
            public virtual DbSet<Store> Stores { get; set; }  
      
    //        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    //        {  
    //            if (!optionsBuilder.IsConfigured)  
    //            {  
    //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.  
    //                optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");  
    //            }  
    //        }  
      
            //protected override void OnModelCreating(ModelBuilder modelBuilder)  
            //{  
            //    modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");  
      
            //    modelBuilder.Entity<Store>(entity =>  
            //    {  
            //        entity.HasKey(e => e.StorId)  
            //            .HasName("UPK_storeid");  
      
            //        entity.ToTable("stores");  
      
            //        entity.Property(e => e.StorId)  
            //            .HasMaxLength(4)  
            //            .IsUnicode(false)  
            //            .HasColumnName("stor_id")  
            //            .IsFixedLength(true);  
      
            //        entity.Property(e => e.City)  
            //            .HasMaxLength(20)  
            //            .IsUnicode(false)  
            //            .HasColumnName("city");  
      
            //        entity.Property(e => e.State)  
            //            .HasMaxLength(2)  
            //            .IsUnicode(false)  
            //            .HasColumnName("state")  
            //            .IsFixedLength(true);  
      
            //        entity.Property(e => e.StorAddress)  
            //            .HasMaxLength(40)  
            //            .IsUnicode(false)  
            //            .HasColumnName("stor_address");  
      
            //        entity.Property(e => e.StorName)  
            //            .HasMaxLength(40)  
            //            .IsUnicode(false)  
            //            .HasColumnName("stor_name");  
      
            //        entity.Property(e => e.Zip)  
            //            .HasMaxLength(5)  
            //            .IsUnicode(false)  
            //            .HasColumnName("zip")  
            //            .IsFixedLength(true);  
            //    });  
      
            //    OnModelCreatingPartial(modelBuilder);  
            //}  
      
            //partial void OnModelCreatingPartial(ModelBuilder modelBuilder);  
        }  
    }


3. Add the controller
In Solution Explorer, right-click the Controllers folder > Add > New Scaffolded Item. Then, select MVC Controller with views, using Entity Framework > Add.

Complete the Add MVC Controller with Views, using Entity Framework dialog,

    Model class - Store(MVCCallWebAPI.Models.DB)
    Data context class - pubsContext (MVCCallWebAPI.Models.DB)
    Views - Keep the default of each option checked
    Controller name - Change the default StoresController to StoresMVCController
    Select Add

Visual Studio creates,
    A StroesMVC controller (Controllers/StoresMVCController.cs)
    Razor view files for Create, Delete, Details, Edit, and Index pages (Views/StoresMVC/*.cshtml)

The automatic creation of these files is known as scaffolding.

Step 4. Run and Test the app
Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views, shown below, change the controller as StoreMVC and the app name as MVC app:
    <header>    
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">    
            <div class="container">    
                <a class="navbar-brand" asp-area="" asp-controller="StroeMVC" asp-action="Index">MVC app</a>    
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"    
                        aria-expanded="false" aria-label="Toggle navigation">    
                    <span class="navbar-toggler-icon"></span>    
                </button>    
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">    
                    <ul class="navbar-nav flex-grow-1">    
                        <li class="nav-item">    
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>    
                        </li>    
                        <li class="nav-item">    
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>    
                        </li>    
                    </ul>    
                </div>    
            </div>    
        </nav>    
    </header>     


Now, we run the app,

Click MVC app, we got the screen,


This is a MVC app that consumes the  database directly through entity framework.
 
B: Add Web API with Entity Framework Code First
This part will add a ASP.NET Core Web API into the app with Entity Framework code first approach.

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework
    Step 4: Add Swagger client for Web API
    Step 5: Run and Test app

At the end, you have an Web API built in a MVC app. The Web API is consumed by Swagger interface and can be consumed by any other interfaces, such as Postman.

Step 1: Set up a new Database Context
We make a new database context with the same model, Model/Store.cs, and different database, DB_Demo_API:
 
1. Create a new Database Context class, named DB_Demo_APIContext.cs,
    using Microsoft.EntityFrameworkCore;    
      
    #nullable disable    
        
    namespace MVCCallWebAPI.Models.DB    
    {    
        public partial class DB_Demo_APIContext : DbContext    
        {    
            public DB_Demo_APIContext()    
            {    
            }    
        
            public DB_Demo_APIContext(DbContextOptions<DB_Demo_APIContext> options)    
                : base(options)    
            {    
            }    
        
            public virtual DbSet<Store> Stores { get; set; }    
        
        }    
    }     

2. Add the new Connection in the appsettings.json file,
    {        
      "Logging": {        
        "LogLevel": {        
          "Default": "Information",        
          "Microsoft": "Warning",        
          "Microsoft.Hosting.Lifetime": "Information"        
        }        
      },        
            
      "ConnectionStrings": {        
        "DevConnection": "Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"        
      },        
            
      "ConnectionStrings": {        
        "DB_Demo_APIConnection": "Data Source=localhost;Initial Catalog=DB_Demo_API;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"        
      },        
            
      "AllowedHosts": "*"        
    }   


3. Register the database connection context into Class starup.cs inside ConfigureServices,
    public void ConfigureServices(IServiceCollection services)      
    {       
        // Register SQL database configuration context as services.       
        services.AddDbContext<pubsContext>(options =>      
        {  options.UseSqlServer(Configuration.GetConnectionString("DevConnection"));      
        });      
        services.AddDbContext<DB_Demo_APIContext>(options =>      
        {      
            options.UseSqlServer(Configuration.GetConnectionString("DB_Demo_APIConnection"));      
        });      
          
        services.AddControllersWithViews();      
    }     


Step 2: Work with a database using Entity Framework code first appoach.
Click "Tools->NuGet Package Manager->Package Manager Console"(See A-Step 2), and run the PMC command (make them in one line),
    Add-Migration   
    -Name initialMigration   
    -Context DB_Demo_APIContext     

We got two migration files under Migration folder,

Run PMC command
    Update-Database    
    -Name initialMigration     
    -Context DB_Demo_APIContext       


We got the database table Stores created in database DB_Demo_API

Step 3: Scaffold API Controller with Action using Entity Framework

    Right-click the Controllers folder.
    Select Add > New Scaffolded Item.
    Select API Controller with actions, using Entity Framework, and then select Add.

In the Add API Controller with actions, using Entity Framework dialog,

    Model class -Store(MVCCallWebAPI.Models.DB)
    Data context class - DB_Demo_APIContext (MVCCallWebAPI.Models.DB)
    Controller name - Change the default StoresController to StoresWebAPIController
    Select Add


The generated code,

    Marks the class with the [ApiController] attribute. This attribute indicates that the controller responds to web API requests.
    Uses DI to inject the database context (DB_Demo_APIContext) into the controller. The database context is used in each of the CRUD methods in the controller.

Step 4: Add Swagger client for Web API
Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification.
 
If we created a new Web API project, the Swagger cient for Web API would be installed by default. In our current case, the Web API is created in a MVC module, so we need to install Swagger manually.
 
1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger


There are three main components to Swashbuckle (Swagger), we only need to install two of them: SwaggerGen and SwaggerUI, the Swagger would be included.
 
2.  Register Swagger Client in startup.json file
Add the Swagger generator to the services collection in the Startup.ConfigureServices method,
    // This method gets called by the runtime. Use this method to add services to the container.        
    public void ConfigureServices(IServiceCollection services)        
    {        
        // Register the Swagger generator, defining 1 or more Swagger documents        
        services.AddSwaggerGen(c =>        
        {        
            c.SwaggerDoc("v2", new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });        
        });        
        ......      
    }   


Enable the middleware for serving the generated JSON document and the Swagger UI, in the Startup.Configure method,
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        
    {        
        // Enable middleware to serve generated Swagger as a JSON endpoint.        
        app.UseSwagger();        
            
        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),        
        // specifying the Swagger JSON endpoint.        
        app.UseSwaggerUI(c =>        
        {        
            c.SwaggerEndpoint("/swagger/v2/swagger.json", "MVCCallWebAPI");        
        });        
        ......      
    }      


Now, we are almost ready to run the app.
 
Step 5: Run and Test the app
Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views again, shown below,
    <header>        
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">        
            <div class="container">        
                <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>        
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"        
                        aria-expanded="false" aria-label="Toggle navigation">        
                    <span class="navbar-toggler-icon"></span>        
                </button>        
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">        
                    <ul class="navbar-nav flex-grow-1">        
                        <li class="nav-item">        
                            <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>        
                        </li>        
                        <li class="nav-item">        
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>        
                        </li>        
                        <li class="nav-item">        
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>        
                        </li>        
                    </ul>        
                </div>        
            </div>        
        </nav>        
    </header>       


Now, we run the app,
 

Click Web API, we got the Swagger Client screen,



ASP.NET MVC Hosting - HostForLIFEASP.NET :: In HTML Tags Custom Attribute

clock April 18, 2022 10:41 by author Peter

In versions prior to ASP.NET MVC 3, you could not declare HTML attributes with dashes/hyphens, without creating a custom type that handled dashes for you. Most of you, who have used custom data attributes with dashes in MVC 1 and 2, must be familiar with the Compiler Error CS0746:


If you use attribute name e.g "data-name", you will see an error

error
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access

However in ASP.NET MVC 3, there is a trick that can be used to handle HTML attributes with dashes. Just use ‘underscores’ in your custom data attribute instead of ‘hyphens’. MVC 3 using the HTML helpers, automatically converts these underscores into dashes/hyphens
@Html.HiddenFor(Model => Model.PartnerId, new { ng_model = "PartnerId" })

BASIC
After view will be rendered then it'll be converted as shown below.
<input type="hidden" name="PartnerId" value="1", ng-model="PartnerId" />



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Showing Data Changes Using SQLDependency With SignalR In ASP.NET MVC

clock March 18, 2022 07:37 by author Peter

Here, I am using SQLDependency which notifies us when any changes are done to the data in the database. First, you have to add an empty MVC project and after that, add the SignalR Package which can be added by using NuGet Package Manager.

Add a Controller in your project.
public class HomeController : Controller  
    {  
        // GET: Home  
        public ActionResult Index()  
        {  
            return View();  
        }  
        public JsonResult GetMessages()  
        {  
            List<data> messages = new List<data>();  
            Repository r = new Repository();  
            messages = r.GetAllMessages();  
            return Json(messages,JsonRequestBehavior.AllowGet);  
        }  
    }

Now, add a new class and name it as Repository.
public class Repository  
    {  
        SqlConnection co = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["con"].ConnectionString);  
        public List<data> GetAllMessages()  
        {  
            var messages = new List<data>();  
            using (var cmd = new SqlCommand(@"SELECT [id],   
                [name],[adres] FROM [dbo].[userdata]", co))  
            {  
                SqlDataAdapter da = new SqlDataAdapter(cmd);  
                var dependency = new SqlDependency(cmd);  
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);  
                DataSet ds = new DataSet();  
                da.Fill(ds);  
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
                {  
                    messages.Add(item: new data  
                    {  
                        id = int.Parse(ds.Tables[0].Rows[i][0].ToString()),  
                        name = ds.Tables[0].Rows[i][1].ToString(),  
                        adres = ds.Tables[0].Rows[i][2].ToString()  
                    });  
                }  
            }  
            return messages;  
        }  
 
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e) //this will be called when any changes occur in db table.
        {  
            if (e.Type == SqlNotificationType.Change)  
            {  
                MyHub.SendMessages();  
            }  
        }  
    }

In Models folder, add a class and name it as data.
public class data  
   {  
       public int id { get; set; }  
       public string name { get; set; }  
       public string adres { get; set; }  
   }


Here, you have to add a SignalR Hub Class to you project and name it as MyHub.
[HubName("MyHub")]  
   public class MyHub : Hub  
   {  
 
       [HubMethodName("sendMessages")]  
       public static void SendMessages()  
       {  
           IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();  
           context.Clients.All.updateMessages();  
       }  
   }

Again, you have to add another class named OWIN Startup Class.
public class Startup  
   {  
       public void Configuration(IAppBuilder app)  
       {  
          // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888  
         app.MapSignalR();  
       }  
   }


View(Index)
@{  
    Layout = null;  
}  
 
<!DOCTYPE html>  
 
<html>  
<head>  
    <meta name="viewport" content="width=device-width" />  
    <title>Index</title>  
    <script type="text/javascript" src="~/Scripts/jquery-1.6.4.min.js"></script>  
    <script type="text/javascript" src="~/Scripts/jquery.signalR-2.2.2.js"></script>  
    <script type="text/javascript" src="/signalr/hubs"></script>  
    <script type="text/javascript">  
    $(function () {  
        // Declare a proxy to reference the hub.  
        var notifications = $.connection.MyHub;  
 
        //debugger;  
        // Create a function that the hub can call to broadcast messages.  
        notifications.client.updateMessages = function () {  
            getAllMessages()  
 
        };  
        // Start the connection.  
        $.connection.hub.start().done(function () {  
            alert("connection started")  
            //notifications.onconn();  
            getAllMessages();  
        }).fail(function (e) {  
            alert(e);  
        });  
    });  
 
    function getAllMessages()  
    {  
        var tbl = $('#messagesTable');  
        $.ajax({  
            url: '/Home/GetMessages',  
            contentType: 'application/html ; charset:utf-8',  
            type: 'GET',  
            dataType: 'html'  
        }).success(function (result) {  
            var a2 = JSON.parse(result);  
            tbl.empty();  
            $.each(a2, function (key, value)  
            {  
                tbl.append('<tr>' + '<td>' +value.id + '</td>' + '<td>' + value.name + '</td>' + '<td>' + value.adres + '</td>' + '</tr>');  
            });  
        })  
    }  
    </script>  
</head>  
<body>  
    <div>   
        <table id="tab">  
             
        </table>  
    </div><br/>  
    <div class="row">  
        <div class="col-md-12">  
            <div >  
                <table border="1">  
                    <thead>  
                        <tr>  
                            <th>id</th>  
                            <th>name</th>  
                            <th>address</th>  
                        </tr>  
                    </thead>  
                    <tbody id="messagesTable">  
 
                    </tbody>  
                </table>  
            </div>  
        </div>  
    </div>  
</body>  
</html>   




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Could Not Find A Part Of The Path... bin\roslyn\csc.exe

clock March 15, 2022 09:20 by author Peter

A fix to Roslyn issue when compiling in .NET Code.

Introduction
This is long existing issue, at least since VS 2015.  There are two possible fixes, one is updating the Roslyn to make the code work, another one is deleting Roslyn.  I prefer the latter and will introduce my solution.

The structure of this article:
    Introduction
    Problem
    Two Possible Fixes
        Update the Roslyn compiler
        Delete the Roslyn compiler
    My Fix

Problem
When running a MVC web application, we got this error message:

Possible Fixes
Search online, we saw two possible solutions in one thread: Could not find a part of the path ... bin\roslyn\csc.exe, the suggestions as below:
Update the Roslyn compiler 


Delete the Roslyn compiler,


 

My Fix
I prefer the latter one. This is my solution:
Search entire solution for Microsoft.CodeDom.Providers.DotNetCompilerPlatform


Search entire solution for Microsoft.Net.Compilers

Open Package Manager Console in Visual Studio:

Run the following command if any one of the above existing,
PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers


For ours, we run the first,

Recheck the result,

Microsoft.CodeDom.Providers.DotNetCompilerPlatform is gone,


Recompile and run, the app works.
Check the changes. In Packages.config,

In Web.config,



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Customer Error page In MVC 5.0

clock March 2, 2022 07:25 by author Peter

In this article, we will look at how to manually customize an error page in ASP.NET MVC 5.


MCV Introduction

The MVC architectural pattern separates the user interface (UI) of an application into three main parts.

Model

A set of classes that describes the data you are working with as well as the business logic.

View
Defines how the application’s UI will be displayed. It is pure HTML, which decides how the UI is going to look.

Controller
A set of classes that handles communication from the user, overall application flow, and application-specific logic

When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it is up to the controller to talk to either the database, the file system, or the model.

Why do we need a Custom Error Page?

We would just configure our custom error pages in one place and it would just work, no matter how/where the error was raised. In order to handle exceptions thrown by your action methods, you need to mark your method with the HandleError attribute. The HandleError attribute also allows you to use a custom page for this error.
Steps to be Followed

Step 1
Create a MVC application named “Http500Test”. For this demo, I have used VS 2019 and .NET version 4.7.2


The solution looks like this

Step 2
Create a Controller class file named “CustomerErrorUserController.cs”

[HandleError] attribute provided built-in exception filters. This attribute can be applied over the action method as well as the controller or at the global level.

At CustomerErrorUser/Index, this application will show error.cshtml as the view not found in Index but in the web.config file. The error statusCode="404" means that the file is not found and it means the controller name or controller action method name is the issue.

[HandleError] //If I put in this attribute and run, it will go to the Customized by a Default error page.

Step 3

Create a controller class named “ErrorController.cs”

I have added two action methods – NotFound() and UnhandledException().

Step 4
Go to View/Shared Folder; create two views named “NotFound.cshtml” and “UnhandledException.cshtml”


Put your own code in the NotFound.cshtml file by removing the existing code.

Put your own code in the UnhandledException.cshtml file by removing the existing code.

Step 5
Go to Web.config and. Add some code for “File Not Found” and “UnhandledException”

Output
http://localhost:63217/CustomeErrorUser

How to display UnhandledException?
I have added two lines of code in the About() action method in HomeController.cs

Now run this MVC app and click on “About”

Instead of redirecting to “UnhandledException.cshtml”, the app is showing error.cshtml file
How to show UnhandledException.cshtml?

Visual Studio, by default, is creating two cshtml files, i.e. _Layout.cshtml and Error.cshtml inside the Shared folder.

Since we are using [HanldeError] attribute, all the unhandled exceptions will be redirected to by default error page (Error.cshtml).

There was some boilerplate code left in the FilterConfig.cs when creating the project.

This creates a new instance of HandleErrorAttribute, which is applied globally to all of my views. With no customization, if a view throws an error while utilizing this attribute, MVC will display the default Error.cshtml file in the Shared folder.

Commenting this line out solved the problem and allowed me to use custom error pages for 500 errors.

Again run the application and click on “About”

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Create ASP.NET Core MVC 6.0 Application?

clock February 21, 2022 08:46 by author Peter

Prerequisites
    Install Visual Studio 2022 updated version 17.0 or later.
    Install .NET SDK 6.0

Now let's start creating an ASP.NET Core MVC 6.0 web application.

Step 1 - Install Visual Studio
First, install Visual Studio 2022 in your system.

Step 2 - Open Visual Studio
Open Visual Studio 2022.

 

Step 3
Then click on Continue Without Code as shown in the following image


Step 4
Then from Visual Studio Menu, click on File -> New-> Project, as shown in the following image

Click on the New Project, then the following window appears as shown in step 5.

Step 5- Choose Project Template
You can see various project template types, choose the ASP.NET Core Web App (Model-View-Controller) .this project template creates the web application with Model, View and Controller (MVC), as shown in the following image.

After choosing the project template click on Next

Step 6 - Define Project Name and Location
In the project configuration window you will see the following options,

    Project Name
    Define any name for your project as per your choice. Here I have chosen project name as “Asp.NetCore6Demo”.

    Location
    Choose the location to save the project files on your hard drive of the system. I have chosen the Project/VS folder of the E drive of the system.

     Solution Name
    Solution name is auto-defined based on the project name, but you can change the name based on your own choice. But I have not changed my solution name. Solution name and project name both are same.

Additionally, there is a checkbox, if you have checked it, then the solution file (.Soln) and project files will be saved in the same folder. As shown in the following image.


After defining the required details, click on Next.

 Step 7 - Choose the Target Framework

Choose the target framework .NET 6.0 (Long-term support) which is the latest as shown in the following image.


After providing the required details, click the create button. It will create the ASP.NET Core MVC 6.0 web application as shown in step 8.

Step 8 - ASP.NET Core MVC 6.0 Folder Structure
The following is the default folder structure of the ASP.NET Core MVC 6.0 application.


Step 9 - Run the ASP.NET Core MVC 6.0 Application
You can build and run the application with default contents or let open the Index.cshtml file and put some contents there. Here I have some changes in index page.
Now press F5 on the keyboard or use the run option from Visual Studio to run the application in the browser. After running the application, it will show in the browser.

I hope, you have learned how to create the ASP.NET Core MVC 6.0 Web Application.

In this article, we explained how to create ASP.NET Core MVC 6.0 application. I hope this article is useful and easy to understand.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Swagger For .NET Core MVC Web API

clock February 14, 2022 07:26 by author Peter

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification. Swagger UI is an alternative to Postman.

I used Swagger more than several times in my articles, but just as a minor tool used in different topics. When I tried to get info of Swagger, I had to search from these articles, which were not convinient. So, I rewrite these two articles, especially about Swagger for .NET MVC Web API or .NET Core MVC Web API.

If we created a new .NET Core 5.0 Web API project, the Swagger cient for Web API would be installed by default. In our current case, although we use .NET Core 5.0, the Web API is created in a MVC module, so we need to install Swagger manually. This way will work for the .NET Core version before 5.0.

This article is part of my another article: Consume Web API By MVC In .NET Core (1), Server And Framework, we got Swagger related part here. You can see details from there.
Step 1 - Create an ASP.NET Core MVC application

We use the version of Visual Studio 2019 16.8 and .NET 5.0 SDK to build the app.

    Start Visual Studio and select Create a new project.
    In the Create a new project dialog, select ASP.NET Core Web Application > Next.
    In the Configure your new project dialog, enter MVCCallWebAPI for Project name.
    Select Create.
    In the Create a new ASP.NET Core web application dialog, select,
     
        .NET Core and ASP.NET Core 5.0 in the dropdowns.
        ASP.NET Core Web App (Model-View-Controller).
        Create

Build and run the app, you will see the following image shows the app,


Step 2~3 - Scaffold API Controller with Action using Entity Framework

Please see the article, Consume Web API By MVC In .NET Core (1), Server And Framework,
B: Add Web API with Entity Framework Code First

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework

Step 4 - Add Swagger client for Web API

1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger

Step 2~3 - Scaffold API Controller with Action using Entity Framework

Please see the article, Consume Web API By MVC In .NET Core (1), Server And Framework,
B: Add Web API with Entity Framework Code First

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework

Step 4 - Add Swagger client for Web API

1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger


There are three main components to Swashbuckle (Swagger), we only need to install two of them: SwaggerGen and SwaggerUI, the Swagger would be included.

2.  Register Swagger Client in startup.cs file
Add the Swagger generator to the services collection in the Startup.ConfigureServices method,
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v2", new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });
    });
    ......
}


Enable the middleware for serving the generated JSON document and the Swagger UI, in the Startup.Configure method,
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v2/swagger.json", "MVCCallWebAPI");
    });
    ......
}

Now, we are almost ready to run the app.

Step 5 - Run and Test the app

Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views again to add Swagger (line 11~13), shown below,
<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>

Now, we run the app,


Click Web API, we got the Swagger Client screen,


 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Show Dynamic List Using View Bag In ASP.NET MVC?

clock February 2, 2022 08:15 by author Peter

In this blog, we will learn about how we can show the dynamic list using View Bag in ASP.net MVC.

Step 1 - Create a Model
First create the Model and define the public properties of Model.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AspNetMVCPractice.Models {
    public class Employee {
        public int Id {
            get;
            set;
        }
        public string Name {
            get;
            set;
        }
        public string Address {
            get;
            set;
        }
        public string Country {
            get;
            set;
        }
        public string City {
            get;
            set;
        }
        public Department Department {
            get;
            set;
        }
    }
}


Step 2 - Define the Action Method in Controller
public ActionResult Index() {
    return View();
}

Step 3 - Create the List and Pass the Model to that List
The third step is to create the list of Employees inside your Action Method.
public ActionResult Index() {
    List < Employee > list = new List < Employee > () {
        new Employee() {
                Id = 1,
                    Name = "Mudassar",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
            new Employee() {
                Id = 2,
                    Name = "Asad",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
            new Employee() {
                Id = 3,
                    Name = "Mubashir",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
    };
    ViewBag.model = list;
    return View();
}

Step 4 - Pass the List to View bag
Pass the data of list to view bag using model,
List < Employee > list = new List < Employee > () {
    new Employee() {
            Id = 1,
                Name = "Peter",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
        new Employee() {
            Id = 2,
                Name = "Jan",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
        new Employee() {
            Id = 3,
                Name = "Rudolph",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
};
ViewBag.model = list;


Step 5 - Show the Data on Front End
Given below code is to show the dynamic list of data using view bag in asp.net MVC.
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="wrapper">
  <div class="container">
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">Name</th>
          <th scope="col">Address</th>
          <th scope="col">City</th>
          <th scope="col">Country</th>
        </tr>
      </thead>
      @foreach (var item in ViewBag.model)
       {
      <tbody>
        <tr>
          <th scope="row">@item.Id</th>
          <td>@item.Name</td>
          <td>@item.Address</td>
          <td>@item.City</td>
          <td>@item.Country</td>
        </tr>
      </tbody>             }
    </table>
  </div>
</div>



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Attribute Routing in ASP.Net MVC 5.0

clock January 28, 2022 06:27 by author Peter

Routing is a pattern matching process that monitors the requests and determines what to do with each request. In other words we can say Routing is a mechanism for mapping requests within our MVC application.

When a MVC application starts the first time, the Application_Start () event of global.asax is called. This event registers all routes in the route table using the RouteCollection.MapRoute method.

Example
    routes.MapRoute(  
        "Default", // Route name  
        "{controller}/{action}/{id}", // URL with parameters  
        new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  
    );


MVC 5 supports a new type of routing called “Attribute Routing”. As the name suggests, Attribute Routing enables us to define routing on top of the controller action method.

Enabling Attribute Routing
To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration.
    public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
            routes.MapMvcAttributeRoutes();  
        }  
    }


We can also add a customized route within the same method. In this way we can combine Attribute Routing and convention-based routing.
    public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
            routes.MapMvcAttributeRoutes();   
            routes.MapRoute(  
                   "Default", // Route name  
                    "{controller}/{action}/{id}", // URL with parameters  
                    new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  
               );  
        }  
    }


Attribute Routing Example
A route attribute is defined on top of an action method. The following is the example of a Route Attribute in which routing is defined where the action method is defined.

In the following example, I am defining the route attribute on top of the action method
    public class HomeController : Controller  
    {  
        //URL: /Mvctest  
        [Route(“Mvctest”)]  
        public ActionResult Index()  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
    }}   

Attribute Routing with Optional Parameter
We can also define an optional parameter in the URL pattern by defining a question mark (“?") to the route parameter. We can also define the default value by using parameter=value.
    public class HomeController : Controller  
    {  
      
      // Optional URI Parameter  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
      
        [Route(“Mvctest /{ customerName ?}”)]  
        public ActionResult OtherTest(string customerName)  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
      
       // Optional URI Parameter with default value  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
      
       [Route(“Mvctest /{ customerName =0036952}”)]  
       public ActionResult OtherTest(string customerName)  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Route Prefixes
We can also set a common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute.

Example
    [RoutePrefix(“Mvctest”)]  
    public class HomeController : Controller  
    {  
        // URL: /Mvctest/  
        [Route]  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
      
      // Optional URI Parameter  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
        [Route(“{ customerName }”)]  
        public ActionResult OtherTest(string customerName)  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


When we use a tide (~) sign with the Route attribute, it will override the route prefix.

Example
    [RoutePrefix(“Mvctest”)]  
    public class HomeController : Controller  
    {  
        // URL: /NewMvctest/  
        [Route(“~/NewMVCTest”)]  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Defining Default Route using Route Attribute
We can also define a Route attribute on top of the controller, to capture the default action method as the parameter.

Example
    [RoutePrefix(“Mvctest”)]  
    [Route(“action=index”)]  
    public class HomeController : Controller  
    {  
        // URL: /Mvctest/  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }   
      
        // URL: /Mvctest/NewMethod  
        public ActionResult NewMethod()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }

Defining Route name
We can also define a name of the route to allow easy URI generation.

Example
    [Route(“Mvctest”,  Name = "myTestURL")]  
    public ActionResult Index()  
    {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
    }


We can generate URI using Url.RouteUrl method.
    <a href="@Url.RouteUrl("mainmenu")">Test URI</a>  

Defining Area
We can define the "Area" name from the controller that belongs to the using RouteArea attribute. If we define the “RouteArea” attribute on top of the controller, we can remove the AreaRegistration class from global.asax.
    [RouteArea(“Test”)]  
    [RoutePrefix(“Mvctest”)]  
    [Route(“action=index”)]  
      
    public class HomeController : Controller  
    {  
        // URL: /Test/Mvctest/  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Attribute Routing gives us more control over the URIs in our MVC web application. The earlier way of routing (convention-based routing) is fully supported by this version of MVC. We can also use both type of routing in the same project.

    Attribute Routing with Optional Parameter



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in