gpt4 book ai didi

c# - 产生数据注释

转载 作者:太空狗 更新时间:2023-10-29 17:43:04 25 4
gpt4 key购买 nike

我最近一直在学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com