c# - 产生数据注释

标签 c# asp.net-web-api asp.net-core asp.net-core-mvc

我最近一直在学习 Web API,并计划使用它来提高我的 MVC 应用程序的可扩展性。但是,当我最终开始创建 Web API Controller 时,我发现了应用于 Controller 类的 [Produces("application/json")] 注释。我一直无法弄清楚该注释的作用。我希望 Controller 只接受 json 输入,那么这个标签对我有帮助吗?

最佳答案

ProducesAnnotation 只关心响应格式。所以这对您限制输入的需求没有帮助。

您可以使用 ASP.NET Core MVC 框架中的 ProducesAnnotation 将内容协商过程定向到 Controller 操作输出的特定类型或特定操作。 来自文档(https://docs.asp.net/en/latest/mvc/models/formatting.html):

If you would like to restrict the response formats for a specific action you can, you can apply the [Produces] filter.

如果您想在全局级别限制对 json 的输入,您可以在启动时将 MVC 配置为在您的 Startup.cs 中只有一个类型为 JsonInputFormatter 的 InputFormatter。

public void ConfigureServices(IServiceCollection services)
{
    ...    
    // Add framework services.
    services.AddMvc(config =>
    {
        // Add XML Content Negotiation
        config.RespectBrowserAcceptHeader = true;
        config.InputFormatters.Clear();
        config.InputFormatters.Add(new JsonInputFormatter());
    });
    ...
}

在 Controller 或 Action 级别上,[Produces] 的对应项是 [Consumes] Annotation。与

[Consumes("application/json")]
public class MyController : Controller
{
    public IActionResult MyAction([FromBody] CallModel model)
    {
        ....
    }
}

仅当客户端提供 application/json 的 Content-Type header 时,对该 Controller 的调用才会成功。否则将返回 415(不支持的媒体类型)。

希望这对您有所帮助。

关于c# - 产生数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414840/

相关文章:

c# - 依赖注入(inject)抽象库

c# - Blazor - 导航和状态问题

c# - 如何通过 DllImport 将 double 组从 C# 传递到 C++

c# - 如何限制 asp.net 中 XML 记录中显示的字符数?

c# - 将自定义 .NET ORM 迁移到 Entity Frame/Dapper

c# - Web API HttpResponseMessage 内容返回不完整

c# - 使用动态属性搜索 LINQ 中的 Where 子句

c# - 多态与职责划分 : how to avoid 'switching on type'

c# - HttpResponseMessage 和 HttpResponseException 有什么区别

asp.net - 使用 Okta 配置 JWT token 的 Swagger 授权