CSV Media Type Formatter for ASP.NET Web API

2019-09-15 19:51发布

问题:

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)

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;
    } 

For "type" in the CsvFormatter i get a:

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

with

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

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

回答1:

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?

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;
}