Search code examples
c#asp.net-mvcasp.net-web-apiasp.net-mvc-5asp.net-web-api2

How to return File with custom Message


I use HttpResponseMessage to return a file to front-end :

public HttpResponseMessage Post(string version, string environment,
string filetype)
{
    var path = @"C:\Temp\a.txt";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
    new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

The question is how can i also return message along with the file ?I thought it has limit if adding the message to custom header .

Edit :

The use-case here is the action will create a lot of files , zip the files and return the zip file to front-end , but the problem is the some of the files are not successfully created i need to return the file names to front-end , i can create logs in database but the question is the front-end doesn't know the log id or some other info to identify the specific log.


Solution

  • The simple answer is: You can't.

    Content-Type: application/octet-stream sets the, well, content type, and as such the browser will assume that the bytes that are part of the content are a binary file.

    What is the use-case here? Maybe you can use Multipart, as is used for E-Mails, but in general just having separate requests/endpoints would be the typical solution. You could even append a query parameter such as ?message to the existing endpoint