C# Web Applications
Tags: csharp, beginners, codenewbie, webdev
Published: 2021-04-25 17:09:59

# Clients and Servers **Terminology**

---

- **Client**: A computer program that sends a request to another program for data or services (e.g., a web browser is a client that sends requests to a web server).
- **Server** or **Web Server**: A computer program or device that uses HTTP to distribute information to a client.
- **Internet Protocol (IP) Address**: A set of numbers separated by periods that uniquely identifies a device on the Internet.
- **Port number**: Part of the addressing information used to identify the sender/receiver of requests at an IP address (e.g., 43 is the port number with this IP address: 198.185.159.145:43).
- **Internet Service Provider (ISP)**: A company that provides access to the Internet and assigns an IP address to the connecting device.
- **Hypertext Transfer Protocol (HTTP)**: A protocol that defines how requests are formatted, transmitted and processed between web clients and web servers.
- **Domain Naming System (DNS) Servers**: The "address book" of the Internet; servers that maintain all domain names and translate them to Internet Protocol (IP) addresses.
- **Web Resource**: The target of a web address; Examples of web resources include files, documents, images, videos, stylesheets, scripts.

# **Additional Resources**

---

To further explore any of these concepts, visit the following articles linked in this lesson:

- [Web Server](https://en.wikipedia.org/wiki/Client%E2%80%93server_model)
- [Client](https://en.wikipedia.org/wiki/Client_(computing))
- [IP Address](https://en.wikipedia.org/wiki/IP_address)
- [Internet Service Provider (ISP)](https://en.wikipedia.org/wiki/Internet_service_provider)
- [Hypertext Transfer Protocol (HTTP)](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)
- [Domain Naming System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System)

# Uniform Resource Locator  **Terminology**

---

- **Uniform Resource Identifier (URI)/Uniform Resource Locator (URL)**: The web address which specifies the location of the requested web resources.
- **Scheme**: The part of the URL that indicates the protocol to be used in communication (e.g. `http://`).
- **Host**: The part of the URL that contains the domain name.
- **Path**: The part of the URL that contains the resource name.
- **Query string**: An optional part of a URL that contains parameters for querying a database; begins with the `?` symbol; often used in a search request.
- **Fragment**: An optional part of a URL that contains details for where the browser should display the information (e.g. on a particular `div`).

# **Additional Resources**

---

- [Uniform Resource Locator](https://en.wikipedia.org/wiki/Uniform_Resource_Locator)

# Introduction to [ASP.NET](http://asp.net/) Core

**ASP.NET Core MVC**: A Model-View-Controller framework based on C#.

**Server-side framework**: An application that runs on a server, not in a client such as a browser.

.NET has three different implementations:

- .NET Framework
- .NET Core
- Xamarin with Mono

# Server-Side Rendering **Terminology**

- **Server-side application**: An application that uses a server to serve content to a client.
- **Client**: Usually a web browser but can be anything that facilitates interaction with the web.
- **Server**: A machine that contains resources (like web pages and files).
- **HTTP response**: When a server responds to a client's request via HTTP.
- **HTTP request**: When a client such as a browser makes a request to a client.
- **DNS server**: A server that looks up an IP address by resolving a domain name.
- **Domain name**: The name we type in to go to a specific webpage.
- **IP address**: Short for internet protocol. The actual numerical address where a site's content lives.
- **Request-response loop**: Ongoing communication between a client and a server.
- **Client-side**: When content for an application is served through a client like a browser instead of a server. The server is contacted once and all content for a site is provided. JavaScript applications are often client-side.

# MVC Pattern

ASP.NET MVC is a **server-side** **MVC** framework.

The **MVC** in *ASP.NET MVC* stands for **Model-View-Controller**, which consists of the following:

- The **model** represents data.
- The **view** is the part of the application the user sees.
- The **controller** acts as a bridge between models and views.

# Constructing and Configuring an [ASP.NET](http://asp.net/) Core Project

### **Sample `.csproj` File**

**ProjectName/ProjectName.csproj**

```csharp
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
</Project>
```

### **Sample `Startup.cs` File**

**ProjectName/Startup.cs**

```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ProjectName
{
  public class Startup
  {
    public Startup(IWebHostEnvironment env)
    {
      var builder = new ConfigurationBuilder()
          .SetBasePath(env.ContentRootPath)
          .AddEnvironmentVariables();
      Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
      app.UseRouting();

      app.UseEndpoints(routes =>
      {
        routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
      });

      app.Run(async (context) =>
      {
        await context.Response.WriteAsync("Hello World!");
      });
    }
  }
}
```

### **Sample `Program.cs` File**

**ProjectName/Program.cs**

```csharp
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace ProjectName
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

      host.Run();
    }
  }
}
```

# Building and Running an [ASP.NET](http://asp.net/) Core MVC Web Application

**MSBuild**: Also known as Microsoft Build Engine or Microsoft Build Tools. It turns code in a project directory into a cohesive application. Run the following to build:

```
> dotnet build
```

After restoring (`dotnet restore`) and building, run a .NET application with the following command in the root directory of the project:

```
> dotnet run
```

Navigate to http://localhost:5000 to see the running .NET application.

The `.gitignore` in our .NET projects should include the following:

**.gitignore**

```
obj/
bin/
```

# Adding a Watcher

Use a file watcher so the server doesn't need to be restarted whenever code is changed:

```
dotnet watch run
```

# Introduction to Controllers, Routes and URLs

# **Sample Controller**

**FriendLetter/Controllers/HomeController.cs**

```csharp
using Microsoft.AspNetCore.Mvc;

namespace FriendLetter.Controllers
{
  public class HomeController : Controller
  {

    public string Hello() { return "Hello friend!"; }

    public string Goodbye() { return "Goodbye friend."; }

  }
}
```

# Custom URL Paths

**Route decorator**: Provides additional information to a route we define. The syntax looks like this:

```
[Route("/name-of-route-goes-here")]
```

**Root path**: The home page for our site. We can use a route decorator to specify a home page:

```
[Route("/")]
```

# Creating and Using Views

- Views in .NET use the `.cshtml` extension.
- The `View()` method has built-in functionality to locate views by name:
    - Because views should **always** reside in a `Views` directory, `View()` first locates the `Views` directory in the production project.
    - Then the method looks for a subdirectory with a name that matches the controller name.
    - Once in the subdirectory, the method then looks for a file that corresponds with the controller's route name (not the route decorator).

    # Creating a Basic Model

    **Sample Model**

    - Models always reside in a `Models` subdirectory of the production project.

    **ProjectName/Models/ClassName.cs**

    ```csharp
    namespace ProjectName.Models
    {
      public class ClassName
      {

      }
    }
    ```

    # Dynamic Views with Razor View Engine

    **Model binding**: Passing data from one part of an application to another.

    Razor syntax looks like this:

    ```csharp
    @Model.PropertyName
    ```

    We need to pass the model in via the `View()` method so that the view has access to it:

    ```csharp
    return View(nameOfModel);
    ```

    # Using Forms with MVC

    **Sample Form**

    We add forms to a route like this:

    ```csharp
    [Route("/form")]
    public ActionResult Form() { return View(); }
    ```

    A form generally looks something like this:

    **FriendLetter/Views/Home/Form.cshtml**

    ```html
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset='utf-8'>
        <title>Create a Custom Postcard!</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
      </head>
      <body>
        <h1>Fill in your name and your friend's name to create your custom postcard!</h1>
        <form action="/postcard" method="post">
         <label for="sender">Sender's Name</label>
         <input id="sender" name="sender" type="text">
         <label for="recipient">Recipient's Name</label>
         <input id="recipient" name="recipient" type="text">
         <button type="submit">Go!</button>
        </form>
      </body>
    </html>
    ```

    Forms have a `<form>` tag with an `action` and `method` This tells ASP.NET Core MVC *where* to submit info provided through this form. **This attribute must be set to the path of another route in our controller.**

    # Debugging Views

    Sometimes we have written a good program that compiles nicely. We build the project, run the server, and navigate to our app. At some point while navigating through our pages, we get an error and a page isn't returned. This generally results in a 500 server error message in the browser. (We'll cover server messages later.) Unfortunately, this vague message isn't helpful for debugging our code.

    In `Startup.cs`, we can add a service that will provide a more detailed error message when a Razor page fails to load due to a server error. Within the `Configure()` method - the same method that declares `app.UseMvc()` - add a new line of code:

    **Startup.cs**

    ```csharp
    ...
        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();  //This is the new line of code
            ...
    ```

    This will produce a friendly error report when Razor fails to load.