【问题标题】:What kind of datatypes should I use for the return value of a Web API method?Web API 方法的返回值应该使用哪种数据类型?
【发布时间】:2014-02-17 12:09:48
【问题描述】:

我有一个将数据返回给我的客户端的 Web API 控制器。代码如下所示:

    [HttpGet]
    [ActionName("Retrieve")]
    public IEnumerable<Reference> Retrieve(int subjectId)
    {
        return _referenceService.Retrieve(subjectId);
    }

谁能告诉我有必要指定 ActionName 吗?

我还应该返回一个 IEnumerable、一个 IList 还是其他什么?

【问题讨论】:

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


    【解决方案1】:

    我相信如果您的 ASP.NET 路由设置正确,您不需要指定 ActionName,例如:

    protected void Application_Start()
    {
        RouteTable.Routes.MapHttpRoute("0", "{controller}/{action}/{arg1}");
    }
    

    将匹配/YourControllerName/Retrieve/132

    您返回的内容完全基于您的媒体类型格式化程序,其中默认为XmlFormatter 和JsonFormatter。这些可以在GlobalConfiguration.Configuration.Formatters 中找到,并将根据客户端提供的Accept 标头进行选择。

    例如,我们将JSON.Net 用于我们的响应格式,由以下人员配置:

    protected void Application_Start()
    {
        RouteTable.Routes.MapHttpRoute("0", "{controller}/{action}/{arg1}");
    
        MediaTypeFormatterCollection formatters = GlobalConfiguration.Configuration.Formatters;
        formatters.Remove(formatters.XmlFormatter);
    
        var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
        jsonFormatter.Formatting = Formatting.Indented;
        jsonFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
    

    这告诉 WebApi 禁止任何 XML 格式,并且仅使用提供的 JSON.Net 合同解析器返回 JSON。 JSON.Net 支持序列化IEnumerable。

    不过,我建议改为返回 HttpResponseMessage。这也允许您设置状态代码(这仍然使用媒体类型格式化程序,它只是一个更干净的包装器)。你可以这样使用:

    [HttpGet]
    public HttpResponseMessage Retrieve(int subjectId)
    {
        var response _referenceService.Retrieve(subjectId);
    
        return Request.CreateResponse(HttpStatusCode.OK, response);
    }
    

    【讨论】:

    • 非常感谢您的帮助。我会按照你建议的方式去做。如果从检索中没有返回任何内容怎么办。有什么办法可以解决吗?
    • 我只是运行一个序列化空集合的测试(例如:IEnumerable&lt;Reference&gt; references = new List&lt;Reference&gt;();); Json.Net 将一个空集合序列化为一个空数组(例如:[])。
    【解决方案2】:

    如果没有要求,您应该返回 HttpStatusCode 而不是数据,例如 POST 方法应该返回 OK 或其他。 或者如果想要像 Get 方法这样的记录应该返回记录类型。

    您也不需要在 Get、Put、Delete 等方法上添加属性,因为 webapi 会根据操作自动检测方法,例如如果您正在获取数据,那么您的方法名称应该以 Get 开头,例如 GetEmployee 等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多