search
HomeBackend DevelopmentC#.Net TutorialDetailed comparison of several versions of WebApi in ASP.Net Core (picture)

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
        };
      }
    }
  }

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!

Statement
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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.