Web API 自定义文件内容的定制类
public class FileContent : HttpContent { private readonly Stream _stream; public FileContent(string path, string mediaType = "application/octet-stream") { _stream = new FileStream(path, FileMode.Open, FileAccess.Read); Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaType); } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return _stream.CopyToAsync(stream); } protected override bool TryComputeLength(out long length) { if (_stream.CanSeek) { length = _stream.Length; return true; } length = 0; return false; } protected override void Dispose(bool disposing) { _stream.Dispose(); } }
调用
string path = @"H:\0各类知识练习\MyWebApi\WebApi\Img\1.jpg"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new FileContent(path) //默认提示下载 //Content = new FileContent(path,"image/jpg") //直接显示图片 }; return response;