.net core使用request,response,下载文件,下载excel等
电脑版发表于:2019/2/11 15:21
使用request获取内容
net core中request没有直接的索引方法,需要点里边的Query,或者form
string base64 = Request.Form["filecontent"];
Query:
string base64 = Request.Query["filecontent"];
使用response输出字符串
方法1:
Response.Body.Write(System.Text.Encoding.UTF8.GetBytes("新年快乐")); Response.Body.Write(System.Text.Encoding.UTF8.GetBytes("<br/>")); Response.Body.Write(System.Text.Encoding.UTF8.GetBytes("早生贵子"));
方法2:
using (StreamWriter writer = new StreamWriter(Response.Body)) { writer.Write("新年快乐"); writer.Write("<br/>"); writer.Write("早生二胎"); }
这样可以输出但是有出现中文乱码
修改一下response的编码方式就可以了,可以直接设置ContentType
Response.ContentType = "text/html;charset=UTF-8";
然后输出就正常了:
.net core3.0中使用了response无法输出内容
应该是和返回的IActionResult冲突了,把action返回值修改成void即可
使用response输出文件,下载文件
using (FileStream fs = new FileStream(filePath, FileMode.Open)) { byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/octet-stream;charset=UTF-8";; string newName = Guid.NewGuid().ToString().Replace("-", ""); Response.Headers.Add("Content-Disposition", "attachment; filename=" + newName + "." + tnblogResourceDTO.Suffix); Response.BodyWriter.WriteAsync(bytes); Response.BodyWriter.FlushAsync(); }
使用response下载excel
//把内存流做为文件下载中转 MemoryStream memoryStream = new MemoryStream(); workbook.Write(memoryStream); //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/octet-stream;charset=UTF-8"; ; string newName = Guid.NewGuid().ToString().Replace("-", ""); Response.Headers.Add("Content-Disposition", "attachment;filename=" + WebUtility.UrlEncode("用户信息表.xls")); //Response.Headers.Add("Content-Disposition", "attachment;filename=用户信息表.xls"); Response.BodyWriter.WriteAsync(memoryStream.ToArray()); Response.BodyWriter.FlushAsync();
这里下载名称做了一下url编码不然遇到中文下载会报错:InvalidOperationException: Invalid non-ASCII or control character in header: 0x7528
未完待续,新年快乐走一波