最近写接口,然后需要返回文件流。
接口如下:
[System.Web.Http.HttpPost]
public HttpResponseMessage GetFileFromWebApi(Params form)
{
try
{
string dbcode = form.dbcode;
string sysid = form.sysid;
if (dbcode.Contains("_METADATA"))
{
dbcode = dbcode.Replace("_METADATA", string.Empty);
}
// 获取文件根路径
string filePath_fromDb = "";
DataTable filePath = commonService.SelectFilePath(dbcode);
if (filePath != null && filePath.Rows.Count > 0)
{
filePath_fromDb = filePath.Rows[0]["FILEPATH"].ToString();
}
else
{
return new HttpResponseMessage(HttpStatusCode.NotFound); ;
}
// 获取文件名字
string fileName = commonService.GetDigitFileNameByDbCodeAndSYSID(dbcode, sysid);
if (string.IsNullOrEmpty(fileName))
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
// 通过名字获取dir
string dirName = commonService.GetDirByName(fileName);
string absPath = Path.Combine(filePath_fromDb, dbcode, "Pages", dirName, fileName);
if (!File.Exists(absPath))
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var FilePath = absPath;
var fileStream = new FileStream(FilePath, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)
};
return response;
}
catch (Exception ex)
{
LogOpr.Error(ex.Message);
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
在本地测试postman可以正确返回,但是发布在服务器上就不行了,然后日志记录错误是"对路径“XXXXXXXX.pdf”的访问被拒绝。"
百度了说是这个文件夹没有权限,
然后就针对这个文件夹,右键-属性-安全-编辑-添加-高级-立即查找-在结果中选择iis-iusers–确定-确定。就可以访问了。
注意要选择完全控制,不然还是会报错。