我有三个申请。
第一:IIS
第二:服务(ASP.NET MVC)
第三:客户(Winform)
文件存储在IIS上。
服务公共api下载文件作为基于URL的字节数组。客户端通过扩展名调用服务和存储文件的api。
客户端呼叫服务后,我检查服务,它返回15500字节。但我抓住客户端,它是13个字节。
以下是服务代码:
[HttpGet]
public byte[] DownloadData(string serverUrlAddress, string path)
{
if (string.IsNullOrWhiteSpace(serverUrlAddress) || string.IsNullOrWhiteSpace(path))
return null;
// Create a new WebClient instance
using (WebClient client = new WebClient())
{
// Concatenate the domain with the Web resource filename.
string url = string.Concat(serverUrlAddress, "/", path);
if (url.StartsWith("http://") == false)
url = "http://" + url;
byte[] data = client.DownloadData(url);
return data;
}
}
以下是客户端上的代码:
static void Main(string[] args)
{
byte[] data = GetData();
File.WriteAllBytes(@"E:\a.pdf", data);
}
public static byte[] GetData()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:54220/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("API/File/DownloadData?serverUrlAddress=www.x.com&path=Data/Folder/file.pdf").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsByteArrayAsync().Result;
return yourcustomobjects;
}
else
{
return null;
}
}
}
答案 0 :(得分:0)
返回CLR类型时,Web API会尝试基于Xml或Json序列化程序序列化对象。这些都不是你想要的。您想要返回原始字节流。试试这个。
[HttpGet]
public HttpResponseMessage DownloadData(string serverUrlAddress, string path)
{
if (string.IsNullOrWhiteSpace(serverUrlAddress) || string.IsNullOrWhiteSpace(path))
return null;
// Create a new WebClient instance
using (WebClient client = new WebClient())
{
// Concatenate the domain with the Web resource filename.
string url = string.Concat(serverUrlAddress, "/", path);
if (url.StartsWith("http://") == false)
url = "http://" + url;
byte[] data = client.DownloadData(url);
return new HttpResponseMessage() { Content = new StreamContent(data) };
}
}
通过返回HttpResponseMessage,您可以更好地控制Web API如何返回响应。默认情况下,StreamContent会将Content-Type标头设置为application/octet-stream
。您可能希望将其更改为' application / pdf'如果你总是返回PDF文件。