0

In my asp.net webapi project I need to return string json data as a file. What is also important I want to have status code of the response set to 200(successful). I found many examples where people use MemoryStream and FileStreamResult to get proper file from the server but it doesn't work for me.

Unfortunately I always get message in the browser which is "Unexpected error", although the serwer code works without any exceptions. I checked details of the request in a browser and it has status code "Bad request" (400).

My code:

[HttpGet()]
public async Task<IActionResult> Download()
{
    string jsonData = "example data";
    byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
    var stream = new MemoryStream(byteArray);

    var result  =  new FileStreamResult(stream, new MediaTypeHeaderValue("text/json"))
                       {
                           FileDownloadName = "testFile.json"
                       };
    return result;
}
Ellbar
  • 3,984
  • 6
  • 24
  • 36
  • It does seem a bit like you're looking for [something answered in this question](http://stackoverflow.com/questions/41383338/how-to-download-a-zipfile-from-a-dotnet-core-webapi/41395761#41395761). Have you tried `return Created(result);`? – Juliën Feb 27 '17 at 16:37
  • It doesn't work for me :(. Now I get message: ERR_INVALID_RESPONSE. Please use your example as a stream based on string variable instead of getting it from actual existing file on the server. – Ellbar Feb 28 '17 at 05:27

1 Answers1

0
    [HttpGet()]
    public async Task<HttpResponseMessage> Download()
    {
        string jsonData = "example data";
        byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);

var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new ByteArrayContent(byteArray)};
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(Inline) { FileName = "testFile.json" };
            return result;

    }
agfc
  • 852
  • 1
  • 6
  • 13
  • I cannot compile your solution because of 2 the errors: (1): 'FileStreamResult' does not contain a definition for 'Content' and no extension method 'Content' accepting a first argument of type 'FileStreamResult' could be found (2): Cannot implicity convert type System.Net.Http.StringContent to System.Net.Http.HttpResponseMessage – Ellbar Feb 27 '17 at 14:26
  • Sorry. Try this one. – agfc Feb 27 '17 at 16:31
  • Now the code compiles but the result is returned in the browser as a json, not as a file which is downloaded. – Ellbar Feb 28 '17 at 05:18