1.当想通过代码控制访问时使用
2.可用于跨域的控制,因为经过controller
public HttpResponseMessage Doc(string id,string filename)
{
try
{
if (string.IsNullOrEmpty(id))
{
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotFound,
Content = new StringContent("404")
};
}
//todo 解析id为相对路径
// string Extension = Path.GetExtension(id).ToLower();
string path = HostingEnvironment.MapPath(id);
if (string.IsNullOrEmpty(filename))
{
filename= System.IO.Path.GetFileName(path);
}
MemoryStream ms = new MemoryStream(System.IO.File.ReadAllBytes(path));
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(ms),
};
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
return response;
}
catch (Exception ex)
{
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.NotFound,
Content = new StringContent("404")
};
}
#endregion
}