从WCT Restful服务中消费FileStream
本文关键字:FileStream 服务 WCT Restful | 更新日期: 2023-09-27 18:10:25
我已经创建了一个WCF Restful服务,代码如下:
接口:
[ServiceContract]
public interface ISIGService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetMultimedia/{id}")]
Stream GetMultimedia(string id);
}
实现服务的代码:
public Stream GetMultimedia(string id)
{
string filePath = MultimediaBLL.GetFilePath(int.Parse(id));
if (string.IsNullOrEmpty(filePath))
return null;
try
{
FileStream multimediaFileStream = File.OpenRead(filePath);
return multimediaFileStream;
}
catch (Exception ex)
{
Console.WriteLine("Not able to get multimedia stream:{0}", ex.Message);
throw ex;
}
}
我需要使用这个获取多媒体文件(图像,音频或视频)的文件流的服务,到目前为止,我有这个:
RestClient client = new RestClient(urlService);
RestRequest request = new RestRequest
{
Method = Method.GET,
RequestFormat = DataFormat.Xml,
Resource = "GetMultimedia/{id}"
};
request.AddParameter("id", idMultimedia, ParameterType.UrlSegment);
var response = client.Execute(request);
if (!response.StatusCode != HttpStatusCode.OK)
return;
???
我不知道如何获取流并处理它以在处理程序中显示它,像这样:
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader("Content-Length", bytes.Length.ToString());
context.Response.BinaryWrite(bytes);
context.Response.End();
我想我必须得到文件字节发送给处理程序。
我不知道这是不是你想做的事情。
public Stream GetMultimedia(string id)
{
string filePath = MultimediaBLL.GetFilePath(int.Parse(id));
if (string.IsNullOrEmpty(filePath))
return null;
try
{
FileStream multimediaFileStream = File.OpenRead(filePath);
WebOperationContext.Current.OutgoingResponse.ContentType = "Your/contentType";
WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=Your_file_name.png";
return multimediaFileStream;
}
catch (Exception ex)
{
Console.WriteLine("Not able to get multimedia stream:{0}", ex.Message);
throw ex;
}
}
RestClient client = new RestClient(urlService);
RestRequest request = new RestRequest
{
Method = Method.GET,
RequestFormat = DataFormat.Xml,
Resource = "GetMultimedia/{id}"
};
request.AddParameter("id", idMultimedia, ParameterType.UrlSegment);
context.Response.Clear();
content.Response.ClearHeaders();
# write original responseStream to the context.Response.OutputStream
request.ResponseWriter = (responseStream) => responseStream.WriteTo(context.Response.OutputStream);
var response = client.DownloadData(request);
# maybe you need to add content type and file name as well
context.Response.AddHeader("Content-Type", "fetch from response");
context.Response.AddHeader("Content-Disposition", "fetch from response");
context.Response.Flush();
context.Response.Close();
context.Response.End();
if (!response.StatusCode != HttpStatusCode.OK)
# do something