简体   繁体   中英

File download from C# not working, I can see in the browser response from the API

I am using a C# api and I call it from the from the UI, I am able to call it and I can see when I inspect the browser response, the returned data from the api, but it didn't force it to download the response. Here is the code I am using in the C# api

var response = HttpContext.Current.Response;
response.Clear();

string fileName = CleanFileName(string.Format("{0} test - {1}.txt", name, DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss")));
response.AddHeader("content-disposition", "attachment; filename = \"" + fileName + "\"");
response.ContentType = "text/csv";
response.AddHeader("Pragma", "must-revalidate");
response.AddHeader("Cache-Control", "must-revalidate");

byte[] byteArray = Encoding.UTF8.GetBytes(mydata);
response.AppendHeader("Content-Length", byteArray.Length.ToString());
response.BinaryWrite(byteArray);

response.End();
response.Flush();

Thanks

Probably you do async call of your API from your client side. In that case you will get all data that returned by API as result of your request and they won't be downloaded automatically.

Try to do something like this from your client side (JS):

window.open(apiDownloadLink, '_blank', '');

It would cause postback and file will be downloaded by browser.

You can find additional information in this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM