yanxu2021 / ExploreCalifornia

C# .NET MVC
0 stars 0 forks source link

Convention-based routing #1

Open yanxu2021 opened 3 years ago

yanxu2021 commented 3 years ago

Convention-based routing

yanxu2021 commented 3 years ago

Web API uses a couple of different techniques for routing a request to the appropriate controller and action method.

  1. The routing table. The routing table is a table of URL path patterns that ASP.NET through to match the requested URL. It goes through them as you've defined them from top to bottom until it finds one that matches, and then it uses that one. In theory, you could route all of the requests for your entire API application with just a single routing rule, but you'd need to be very consistent with your naming conventions. image
yanxu2021 commented 3 years ago

//Startup.cs

using System; using System.Web.Http; using System.Web.Http.ExceptionHandling; using System.Web.Http.Routing; using ExploreCalifornia.Config; using Microsoft.Owin; using Microsoft.Owin.Security; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Owin;

[assembly: OwinStartup(typeof(ExploreCalifornia.Startup))] namespace ExploreCalifornia { public class Startup { public static HttpConfiguration HttpConfiguration { get; set; } = new HttpConfiguration();

    public void Configuration(IAppBuilder app)
    {
        var config = Startup.HttpConfiguration;
        ConfigureWebApi(app, config);
    }

    private static void ConfigureWebApi(IAppBuilder app, HttpConfiguration config)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        app.UseWebApi(config);
    }
}

}

yanxu2021 commented 3 years ago

[assembly: OwinStartup(typeof(ExploreCalifornia.Startup))]

In Startup.cs, look at the Owin startup class. This class will run automatically by the Owin framework when this assembly loads.

OWIN (Open Web Interface for . NET) is a standard for an interface between . NET Web applications and Web servers. It is a community-owned open-source project.

Every OWIN Application has a startup class where you specify components for the application pipeline. There are different ways you can connect your startup class with the runtime, depending on the hosting model you choose (OwinHost, IIS, and IIS-Express).

config.Routes.MapHttpRoute(..); //This setting is the default API route being created and being added to a route's list. A route pattern is being defined within routeTemplate:"api/{controller}/{id}". The route specified here starts with /api which will help differentiate these routes from any routes that try to match with an MVC controller inside the same project. Confusingly, web API and MVC are set up in very much the same way but these are actually completely separate routes. Note that the controller and ID parts of the route are both surrounded with curly braces. This means that these portions of the URL path will be captured into placeholder variables. Web API will place the word controller after this matched portion of the path and then look for a controller class with that name in your project to run it. For example, order would match to the order controller, GET http request would run a method(GetOrders())in that controller class as show below: image

Another built in placeholder name is action. And that stands for the name of the action method to use inside the controller class. It omitted the route here. That's because web API's default convention matches routes using just the controller name, and the http verb. Finally, the ID portion of the URL is marked as optional in the default section of the route definition .Omit from the request and still match this routing rule.

yanxu2021 commented 3 years ago

This part shows how the default routing rule conventions work in web API to turn a request into an action method, then the next thing is how the parameters for those methods are mapped from the request.

yanxu2021 commented 3 years ago

Parameter Binding Conventions: getting data into API In the route definitions there is a parameter named ID being matched from a value in the path. Web API allows us to match parameters from a couple of different locations from the URI and from the request body. For the URI parameters they could either come from the query string or be matched as part of the path. By default, Web API tries to get the value from the URI for simple types, .net primitives(原始的) like integer, Boolean, decimal, string, date time, double and so forth. For more complex types Web API tries to deserialize(反串行化) the value from the message body. image

yanxu2021 commented 3 years ago

//TourController.cs

using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using ExploreCalifornia.DataAccess; using ExploreCalifornia.DataAccess.Models; using ExploreCalifornia.DTOs;

namespace ExploreCalifornia.Controllers { public class TourController : ApiController { AppDataContext _context = new AppDataContext();

    public List<Tour> Get(bool freeOnly = false)
    {
        var query = _context.Tours.AsQueryable();

        if (freeOnly) query = query.Where(i => i.Price == 0.0m);

        return query.ToList();
    }

    public List<Tour> PostSearch(TourSearchRequestDto request)
    {
        var query = _context.Tours.AsQueryable();

        query = query.Where(i => i.Price <= request.MaxPrice
                      && i.Price >= request.MinPrice);

        return query.ToList();
    }

    public IHttpActionResult Put(int id, Tour dto)
    {
        return Ok($"Put {id} {dto.Name}");
    }

    public IHttpActionResult Patch()
    {
        return Ok("Patch");
    }
    public IHttpActionResult Delete()
    {
        return Ok("Delete");
    }
}

}

yanxu2021 commented 3 years ago

Inside the Tourcontroller there are a get method, as well as a post, put, patch, and a delete method. Each of those matches the five most common http verbs used in a rest service. Notice that each method returns just an OK result with a verb name in the body. To verify that these work, hit /api/tours from within Postman doing a get request and see what we get back from the API.