Home > Backend Development > C#.Net Tutorial > Detailed comparison of several versions of WebApi in ASP.Net Core (picture)

Detailed comparison of several versions of WebApi in ASP.Net Core (picture)

黄舟
Release: 2017-09-25 11:10:59
Original
3873 people have browsed it

This article mainly introduces a brief discussion of the comparison of several version controls of ASP.Net Core WebApi. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

1. Benefits of version control:

(1) It helps to launch functions in a timely manner, and Will not disrupt existing systems.

(2) It can also help provide additional features to selected customers.

API version control can be controlled in different ways, as follows:

(1) Append the version in the URL or as a query string parameter,

(2) By customizing headers and by accepting headers

In this post, let’s take a look at how to support multiple versions of ASP.NET Core Web API.

1. Create an asp.net core webapi project and reference the NuGet package: Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 2.0.0

The project and installation package are ready, then we need to add the following code to the ConfigureServices method in Startup.cs:

As you can see, there are 3 different options configured.

  • ReportAPIVersions: This is optional. However, when set to true, the API will return supported version information in the response header.

  • AssumeDefaultVersionWhenUnspecified: This option will be used for requests that do not provide a version. By default, the assumed API version is 1.0.

  • DefaultApiVersion: This option is used to specify the default API version to use when no version is specified in the request. This will default to version 1.0.

This is all the configuration and settings. Now, we will see the different ways to access API versions.

2. Implement version control through QueryString

Open our controller and add the ApiVersion feature on it, as shown in the following code:

The above code is version 1.0. You can also create another controller class with the same name in a different namespace and set the API version to version 2.0. As shown in the picture below:

That’s it. Now go to the browser and access the controller. You should see output from the API version 1.0 controller as it is set to the default. Now append api-version=2 in the URL and you should see the output of the api version 2.0 controller.

## 2. Implemented through URL Path Segment:

Query string parameters are useful, but can be a pain in the case of long URLs and other query string parameters. Instead, a better approach is to add the version in the URL path. For example:

  • api/v1/values

  • api/v2/values

Still above project, you just need to add the following code to the v1 and v2 controllers. As shown below:

Likewise, you need to update the routing parameters to all applicable locations. With this change, a version number is always required when accessing the API interface. You can access version 1.0 through api/v1/values ​​and version 2.0 through api/v2/values ​​by changing the version number in the URL. Simple and looks cleaner.

The test results are as follows:

##3. Implement version control through HTTP HeadersIn the above two methods, the URL needs to be modified to support version control. However, if you want the API's URL to remain clean, the API version information can also be passed by appending an HTTP header. To make this work, you need to configure the ApiVersionReader options. code show as below:

The highlighted line tells us that the header "api-version" is now the expected location for the api version number. Make sure the route properties do not have version details. So tested it and here's the result:

When you provide 2.0 as a value to "api version", it will call the version 2.0 controller and return the output.

Simple and easy to set up. However, now the query string parameter method for versioning will not work. Once the header is set, query string parameters cannot be specified. If you want to support both cases, use QueryStringOrHeaderApiVersionReader instead of HeaderApiVersionReader. The code is as follows:

# Therefore, query string parameters and headers are now supported. The default query string parameter name is api-version, so you can leave the constructor empty, but if a different name is required, you need to provide it. You can also use different names for query string parameters and headers. Remember, we also set ReportApiVersions to true, which returns the version information in the response header. See below.

Now, let’s look at a few more options.

Usage of the MapToApiVersion parameter:

The MapToApiVersion property allows a single API operation to be mapped to any version. In other words, a single controller that supports multiple versions. Controllers may only have version 3 supported API action methods. In this case, you can use MapToApiVersion. Take a look at the code below.

The above code means: the public string Get() method is only supported in version 1.0, and the public string Getv3() method is only supported in version 3.0.

There are pictures and real images, it’s very flexible, I like it very much.

Usage of the Deprecated parameter:

When supporting multiple API versions, some versions will eventually be deprecated over time. To mark one or more API versions as deprecated, simply decorate your controller with Deprecated. This does not mean that API versions are not supported. You can still call that version. It is simply a way to make calling API users aware that the following versions will be deprecated in the future.

Setting Deprecated to TRUE above means that version 1.0 will be deprecated in the future. When accessing our API interface, you can see the following information in the response header, as shown in the figure below:

Usage of the ApiVersionNeutral feature:

ApiVersionNeutral Feature definition This API no longer supports versioning. This is useful for APIs that behave exactly the same regardless of whether they support API versioning or legacy APIs that don't support API versioning. Therefore, you can add the ApiVersionNeutral property to exit from version control.

Get version information (Version Information)

If you want to know which version of the client is being accessed, you can implement this function through the following code :

To sum up, having multiple versions of the API can help roll out enhanced functionality in an efficient way while also making it easier to track changes. In this article, we saw how to add support for multiple versions in the ASP.NET coreWEB API. The nuget package supports versioning via query string parameters, adding path segments in URLs and via headers. It also features version single API operations and the ability to opt out of versions.

Is it possible to implement version control of an API without resorting to third-party packages? There are methods. Let’s not get too carried away. Let’s read on.

4. Ultimate version (without any NuGet package) asp.net core web api version control

Create a new core API project:

Under the VersionControl folder, create a new class NameSpaceVersionRoutingConvention that implements the IApplicationModelConvention interface. The code is as follows:


public class NameSpaceVersionRoutingConvention:IApplicationModelConvention
  {
    private readonly string apiPrefix;
    private const string urlTemplate = "{0}/{1}/{2}";
    public NameSpaceVersionRoutingConvention(string apiPrefix = "api")
    {
      this.apiPrefix = apiPrefix;
    }

    public void Apply(ApplicationModel application)
    {
      foreach (var controller in application.Controllers)
      {
        
        var hasRouteAttribute = controller.Selectors
        .Any(x => x.AttributeRouteModel != null);
        if (!hasRouteAttribute)
        {
          continue;
        }
        var nameSpaces = controller.ControllerType.Namespace.Split('.');
        //获取namespace中版本号部分
        var version = nameSpaces.FirstOrDefault(x => Regex.IsMatch(x, @"^v(\d+)$"));
        if (string.IsNullOrEmpty(version))
        {
          continue;
        }
        string template = string.Format(urlTemplate, apiPrefix, version,
        controller.ControllerName);
        controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel()
        {
          Template = template
        };
      }
    }
  }
Copy after login

Debugging the code found this This method will only be executed when the program is run for the first time, and will not be executed multiple times after that, so it is very efficient.

5. Summary:

The above is the detailed content of Detailed comparison of several versions of WebApi in ASP.Net Core (picture). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template