在.NET Core中不推荐使用ApiController [英] Is ApiController deprecated in .NET Core

查看:2040
本文介绍了在.NET Core中不推荐使用ApiController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

。NET Core中将弃用 ApiController 是真的吗?因为我打算在新项目中使用它,所以问。

Is it true that "ApiController will get deprecated in .NET Core"? Asking since I'm planning to use it in new projects.

推荐答案

更新ASP.NET Core 2.1

从ASP.NET Core 2.1开始,可以使用一组新的类型来创建Web API控制器。您可以使用 [ApiController] 属性为控制器添加注释,该属性启用了一些新功能,例如自动模型状态验证和绑定源参数推断。请参阅文档以获取更多信息:
https://docs.microsoft.com/zh-cn/aspnet/core/web-api/index?view=aspnetcore-2.1#annotate-class-with-apicontrollerattribute

Since ASP.NET Core 2.1 a new set of types is available to create Web API controllers. You can annotate your controllers with the [ApiController] attribute which enables a few new features such as automatic model state validation and binding source parameter inference. See the docs for more information: https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#annotate-class-with-apicontrollerattribute.

自此以来,确实没有特定的 ApiController 类MVC和WebAPI已在ASP.NET Core中合并。但是,MVC的 Controller 类带来了仅在开发Web API时可能不需要的许多功能,例如视图和模型绑定。

There is indeed no particular ApiController class anymore since MVC and WebAPI have been merged in ASP.NET Core. However, the Controller class of MVC brings in a bunch of features you probably won't need when developing just a Web API, such as a views and model binding.

如果您想要不同的东西,则有两种选择:

You've got two options if you want something different:

使用 ControllerBase Microsoft中的code>类.aspNetCore.Mvc.Core 包。

Use the ControllerBase class in the Microsoft.AspNetCore.Mvc.Core package.

创建您的 ApiController 基类。此处的关键是添加 [ActionContext] 属性,该属性会将当前 ActionContext 实例注入该属性:

Create your ApiController base class. The key here is to add the [ActionContext] attribute which injects the current ActionContext instance into the property:

[Controller]
public abstract class ApiController
{
    [ActionContext]
    public ActionContext ActionContext { get; set; }
}

此外,添加 [Controller] 属性归类,以将其标记为MVC控制器发现的控制器。

Also, add the [Controller] attribute to the class to mark it as a controller for the MVC controller discovery.

在我的 MVC 6中的Web API博客文章

这篇关于在.NET Core中不推荐使用ApiController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆