【问题标题】:When and how to use [ResponseType(typeof(...))] correctly?何时以及如何正确使用 [ResponseType(typeof(...))]?
【发布时间】:2016-12-25 03:14:30
【问题描述】:

我正在做一个项目,我有一个带有Get(int id)GetElements()UpdateElement(int id, Element element)AddElement(Element element)DeleteElement(int id) 的基本控制器。 每个方法都使用[Route][Get]... 注释并返回IHttpActionResult

我对@9​​87654329@ 感到困惑。它是干什么用的?何时以及如何正确使用?

我应该写这样的东西吗? [ResponseType(typeof(IEnumerable<Element>))]GetElements()

谢谢!

【问题讨论】:

    标签: asp.net asp.net-web-api asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    [ResponseType()] 属性有助于创建 RESTful Web API 以及通过 Swagger / Swashbuckle 自动生成文档。

    例如,基于 id 返回项目的方法可以这样编写

    public YourClass Get(int id)
    {
        var item = repo.GetById(id);
        return item;
    }
    

    但是,如果找不到该项目,它将返回 null,而不是 404。

    所以最好写成

    [ResponseType(typeof(YourClass))]
    public IHttpActionResult Get(int id)
    {
        var item = repo.GetById(id);
        if (item != null)
        {
            return this.Ok(item);
        }
    
        return this.NotFound();
    }
    

    在这里查看更多用法http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing

    另请参阅自定义 Swashbuckle 以及它如何使用 ResponseType 属性来确定文档https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-swashbuckle-customize/

    【讨论】:

    • 如果端点返回的不是模型,你会在ResponseType 中声明什么...例如流文件。
    • @crush 这是个好问题,我不知道答案。网上好像没有这样的例子
    • 这应该是IActionResult<YourClass> 并用[ProducesResponseType(StatusCodes.Status200OK)][ProducesResponseType(StatusCodes.Status404NotFound)] 装饰
    • 这在撰写本文时是正确的,适用于 MVC 而不是 .NET Core。否决票是不必要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多