I’m adding CSV export to a service implemented with ASP.NET Web API.
Currently I have a view model (containing details of results filtering), which is sent to a Web API controller via a ajax POST request. The JSON response is then rendered on UI. This works just fine.
Now I want to post the same view model to another controller, let us name it ExportController. Then I need to download the file to the user.
My idea:
-
Post the view model to the service, store it somewhere in persistent storage (DB or in-memory cache, does not matter) and return an export token to a user. (By export token I mean a piece of information used to identify this particular export)
-
Then execute a
GETrequest from aniframewith that token in URL
and get the file as the response to this request.
What I have by now, on UI:
var exportUrl = "URL to ExportController"
$.ajax(exportUrl, {
type: 'POST',
contentType: 'application/json',
data: postData
})
.success(function(data) {
// this should download the file
$('#export').attr('src', exportUrl + '&exportToken=' + data);
});
Here ‘#export’ is the iframe element used to download the file.
And here is a raw sketch of export backend:
public class ExportController : ApiController
{
...
// GET /api/Export
public string Get(string exportToken)
{
// get filters from DB
var filters = ExportArgumentProvider.GetFilters(exportToken);
// get data
var result = DataSource.GetData(filters);
return result;
}
// POST /api/Export
public string Post(FilterInput filters)
{
var guid = Guid.NewGuid();
// save filters to DB
ExportArgumentProvider.AddFilter(guid, filters);
return guid.ToString();
}
}
This pseudo-code obviously does not work, please ignore the return type of Get method.
So, questions:
- Is there easier way to make this export (without storing filter state in DB).
- Is this approach sane (state stored in DB etc.), or such tasks should be done in another way?
- Is ASP.NET Web API a good fit for such tasks or I should resort to usual ASP.NET controllers for export?
UPDATE: data posted to the server may exceed URL lenght limits, so passing it via a GET request is not really an option.
For this project I gave up creating clean and RESTful backend and converted
ExportControllerinto a usual MVC controller. Then I was able to change this line inPostmethodinto
and do the same thing with the
Getmethod.I still think that approach with storing filters in DB is much better, but