简体   繁体   English

使用 URL c# 的 Web-Api 版本控制

[英]Web-Api versioning with URL c#

I'm struggling for days now, i'm trying to achieve my API to version with the url suffix.我现在挣扎了好几天,我正在尝试将我的 API 实现为带有 url 后缀的版本。 fe http://localhost/api/v1/sites & http://localhost/api/v2/sites . fe http://localhost/api/v1/sites & http://localhost/api/v2/sites

I was pretty close I guess but suddenly I messed it all up..我猜我已经很接近了,但突然间我把一切都搞砸了。

Many thanks for helping me out.非常感谢您帮助我。

Now i'm receiving: "System.invalidOperationException:' The constraint type 'ApiVersionRouteConstraint' which is mapped to constraint key 'apiVersion' must implement the IhttpRouteConstraint interface.'现在我收到:“System.invalidOperationException:'映射到约束键'apiVersion'的约束类型'ApiVersionRouteConstraint'必须实现IhttpRouteConstraint接口。' on Global.asax.cs在 Global.asax.cs

Global.asax.cs全球.asax.cs

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace HIDDEN
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

WebApiConfig.cs WebApiConfig.cs

using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Owin.Security.OAuth;
using System.Web.Http;
using System.Web.Http.Routing;

namespace HIDDEN
{
    public static class WebApiConfig
        {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services  
            // Configure Web API to use only bearer token authentication.  
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            var contraintResolver = new DefaultInlineConstraintResolver()
            {
                ConstraintMap =
                {
                    ["apiVersion"] = typeof(ApiVersionRouteConstraint)
                }
            };

            // Web API routes  
            config.MapHttpAttributeRoutes(contraintResolver);
            config.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                //o.DefaultApiVersion = new ApiVersion(1, 0);
            });

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

            // WebAPI when dealing with JSON & JavaScript!  
            // Setup json serialization to serialize classes to camel (std. Json format)  
            var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            formatter.SerializerSettings.ContractResolver = new     Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

            // Adding JSON type web api formatting.  
            config.Formatters.Clear();
            config.Formatters.Add(formatter);

        }
    }
}   

RouteConfig.cs路由配置.cs

using System.Web.Mvc;
using System.Web.Routing;


namespace HIDDEN
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

SitesController站点控制器

using FirebirdSql.Data.FirebirdClient;
using System;
using System.Web.Http;
using System.Configuration;
using System.Collections;
using Microsoft.Web.Http;

        namespace HIDDEN.Controllers.V1
        {
        [ApiVersion("1.0")]
        [Route("api/v{version:apiVersion}/[controller]")]

        public class SitesController : ApiController
        {
              //code for V1
        }

        namespace HIDDEN.Controllers.V2
        {
        [ApiVersion("2.0")]
        [Route("api/v{version:apiVersion}/[controller]")]

        public class SitesController : ApiController
        {
              //code for V2
        }
    }

Make sure you are using the correct ApiVersionRouteConstraint as there seems to be a conflict between Microsoft.AspNetCore.Mvc.Routing and Microsoft.Web.Http.Routing确保您使用的是正确的ApiVersionRouteConstraint ,因为Microsoft.AspNetCore.Mvc.RoutingMicrosoft.Web.Http.Routing之间似乎存在冲突

If you are using this versioning library Microsoft.AspNet.WebApi.Versioning you should use Microsoft.Web.Http.Routing如果您正在使用此版本控制库Microsoft.AspNet.WebApi.Versioning您应该使用Microsoft.Web.Http.Routing

using Microsoft.Web.Http.Routing;

In addition you can also add apiVersion constraints to your routes like below此外,您还可以向您的路线添加apiVersion约束,如下所示

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

I think you don't have well configured ASP.Net Web API Versioning我认为你没有配置好 ASP.Net Web API 版本控制

http://www.intstrings.com/ramivemula/articles/asp-net-web-api-versioning/ http://www.intstrings.com/ramivemula/articles/asp-net-web-api-versioning/

You can look at this post, you might have some property without the correct configuration such as:你可以看看这篇文章,你可能有一些没有正确配置的属性,例如:

ReportApiVersions = true;

You can use swagger for better api documentation also for api versioning.您可以使用swagger获得更好的 api 文档,也可以用于 api 版本控制。

Fixed it, biggest problem was the different versions of the controller being in a different namespace.修复它,最大的问题是 controller 的不同版本在不同的命名空间中。

This did the trick:这成功了:

 namespace HIDDEN.Controllers.Sites
 {
     [Authorize]
     [ApiVersion("1.0")]
     [Route("v{version:apiVersion}/sites")]   
     public class valuesV1Controller : ApiController
     {
         // GET: api/values
         public IEnumerable<string> Get()
         {
             return new string[] { "value1", "value2" };
         }
     }

     [Authorize]
     [ApiVersion("2.0")]
     [ApiVersion("2.1")]
     [Route("v{version:apiVersion}/sites")]
     public class valuesV2Controller : ApiController
     {
         // GET: api/values
         public IEnumerable<string> Get()
         {
             return new string[] { "value3", "value4" };
         }
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM