在ASP.NET WebApi中编写自定义路由前缀

时间:2015-08-11 06:13:39

标签: asp.net-mvc

我正在尝试在asp.net WebApi中编写自定义路由前缀。以下是我写的课(跟随一本书)。

public class ApiVersion1RoutePrefixAttribute : RoutePrefixAttribute
 {
    private const string RouteBase = "api/{apiVersion:apiVersionConstraint(v1)}";
    private const string PrefixRouteBase = RouteBase + "/";

    public ApiVersion1RoutePrefixAttribute(string routePrefix)
        : base(string.IsNullOrWhiteSpace(routePrefix) ? RouteBase : PrefixRouteBase + routePrefix) { }

 }

当我构建解决方案时,我收到以下错误:

  

&#34;错误1&#39; WebApiBook.Web.Common.Routing.ApiVersion1RoutePrefixAttribute&#39;:无法从密封类型派生出来#System; Web.Http.RoutePrefixAttribute&#39;&#34; < / p>

这是我的packages.config文件:    enter image description here

1 个答案:

答案 0 :(得分:1)

您正在使用使用Microsoft.AspNet.WebApi.Core version 5.0.0的{​​{1}}并且在此版本中System.Web.Http version 5.0.0被标记为已密封,因此您无法对其进行扩展:

RoutePrefixAttribute

来自namespace System.Web.Http { /// <summary> /// Annotates a controller with a route prefix that applies to all actions within the controller. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class RoutePrefixAttribute : Attribute { /// <summary> /// Gets the route prefix. /// </summary> public string Prefix { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Web.Http.RoutePrefixAttribute"/> class. /// </summary> /// <param name="prefix">The route prefix for the controller.</param> public RoutePrefixAttribute(string prefix) { if (prefix == null) throw Error.ArgumentNull("prefix"); this.Prefix = prefix; } } } 或将您的System.Web.Mvc.RoutePrefixAttribute更新为最新版本。这是5.2.3版的实现。如您所见,该课程不是Microsoft.AspNet.WebApi.Core

selaed