1

My current web API already responding JSON data as below.

public HttpResponseMessage GetFieldInfo()
        {
  //....  
return Ok(GetFieldsInstance());  //GetFieldsInstance returning with DTO class instance.
}

Now, I need to include, file along with JSON response. I could not find any link which shows, how to include filestream and JSON in single response.

For file stream, it will work as below but, not able to find way, how to include JSON object property with filestream.

result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = "FieldFile";
10
  • Your action should return one content type. either JSON or a File. What you can do it create another action that will return the file stream and then include the link to that file in your JSON response along with the other properties. Commented Nov 13, 2017 at 13:52
  • So, create other action itself which return only file. And that controller/action's URL include as property of JSON response (main action). Is it ? Commented Nov 13, 2017 at 13:55
  • Yes that is what I suggested. Commented Nov 13, 2017 at 13:55
  • In that case, it will be separate action URL which is also published. Not sure, one additional URL will allow to publish from business. Commented Nov 13, 2017 at 13:56
  • 1
    You would need to serialize (base64 most likely) the file and add it as property to json for the client to desrialize. If file is big this can cause its own issues. Commented Nov 13, 2017 at 14:10

1 Answer 1

2

You can covert (serialize) the file to a base64 string and include it as a property in the JSON response.

public IHttpActionResult GetFieldInfo() {
    //...

    var model = new { 
        //assuming: byte[] GetBinaryFile(...)
        data = Convert.ToBase64String(GetBinaryFile(localFilePath)), 
        result = "final",
        //...other properties...
    };

    return Ok(model);
}

The client would then need to convert (desrialize) the base64 string back to your desired file to be used as desired.

Take note that depending on the size of the file it can drastically increase the size of the response and the client should take that into consideration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.