用于ASP.NET Web API的CSV媒体类型格式化程序 [英] CSV Media Type Formatter for ASP.NET Web API

查看:115
本文介绍了用于ASP.NET Web API的CSV媒体类型格式化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to implement a CSV MediaTypeFormatter for my Web API as described here: http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format

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

(I don't want to paste in all the code from there)

但是我不能使用下面的Web API Controller来工作. 我使用Fiddler通过以下方式调用Web API: http://myhostname.com/api/csvexport?format = csv

But I don't get it to work using the Web API Controller below. I used Fiddler to call the Web API with: http://myhostname.com/api/csvexport?format=csv

public dynamic Get()
    {

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

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

For "type" in the CsvFormatter i get a:

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

DeclaringMethod = 'type.DeclaringMethod' threw an exception of type 'System.InvalidOperationException'

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

Method may only be called on a Type for which Type.IsGenericParameter is true.

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

So I might not get the concept of the Formatter right and have a problem with the type?

推荐答案

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

You are getting this error because Tugberk's formatter only works for models which implement the generic IEnumerable<T> interface. It makes sense, since people generally want CSV formatted data when they are getting a set of results. If you only want one data entity, why would you want it in CVS format?

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

Your method return type is dynamic, not IEnumerable<T>. You might be able to get it to work by doing something more like this:

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

这篇关于用于ASP.NET Web API的CSV媒体类型格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆