一个cs文件中有多个api控制器类

时间:2016-04-06 18:28:25

标签: c# asp.net-web-api asp.net-web-api2

问题

是否可以在一个文件中包含多个控制器?

示例

位于TestController.cs文件夹中的控制器文件Controllers

TestController.cs

[RoutePrefix("api/v2")]
public class TestController : ApiController
{
     // action methods here...
}

[RoutePrefix("api/v1")]
public class OldTestController " ApiController
{
    // all action methods return an error stating that 
    // the user should update their client to be compatible with 
    // verison 2 of the API.
}
  • GET api/v2/Test将返回数据。
  • GET api/v1/Test将返回错误消息。

描述

我制作了我的Rest API的第2版,其中包括对旧版移动应用程序的更改。

我希望旧路由向用户显示json错误消息,以更新其移动应用。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

文件中可以有多少个控制器没有限制。

为了将控制器标记为过时,一个选项是实现一个ActionFilter来返回你想要的错误。

public class ObsoleteApiAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, "Update your app");
        actionContext.Response = response;
    }
}

然后只应用于您想要返回错误的控制器或方法。

[ObsoleteApi]
[RoutePrefix("api/v1")]
public class OldTestController : ApiController
{
    ...
}