【问题标题】:CSV Media Type Formatter for ASP.NET Web API用于 ASP.NET Web API 的 CSV 媒体类型格式化程序
【发布时间】:2013-03-26 09:25:38
【问题描述】:

我尝试为我的 Web API 实现 CSV MediaTypeFormatter,如下所述: http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format

(我不想从那里粘贴所有代码)

但我无法使用下面的 Web API 控制器使其工作。 我使用 Fiddler 调用 Web API:http://myhostname.com/api/csvexport?format=csv

public dynamic Get()
    {

        var ret = new[] { "CarId", "Make", "Model", "Name" }; 
        return ret;
    } 

对于 CsvFormatter 中的“类型”,我得到一个:

DeclaringMethod = 'type.DeclaringMethod' 引发了类型为 'System.InvalidOperationException' 的异常

方法只能在 Type.IsGenericParameter 为 true 的类型上调用。

所以我可能没有正确理解 Formatter 的概念并且对类型有疑问?

【问题讨论】:

    标签: csv asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您收到此错误是因为 Tugberk 的格式化程序仅适用于实现通用 IEnumerable<T> 接口的模型。这是有道理的,因为人们在获得一组结果时通常需要 CSV 格式的数据。如果你只想要一个数据实体,为什么要 CVS 格式?

    您的方法返回类型是dynamic,而不是IEnumerable<T>。您可能可以通过执行类似这样的操作来使其工作:

    public IEnumerable<string> Get()
    {
        var ret = new[] { "CarId", "Make", "Model", "Name" }; 
        return ret;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 2013-12-10
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      相关资源
      最近更新 更多