[英]How to send an image in C# to client using async method
我有两个C#应用程序。 一个是服务,另一个是客户。 我的服务使用HighCharts.NET创建一个图表。 然后,将图表发送到外部服务器,并以图表形式获取图表。 此方法需要异步,因为我必须等到从服务器成为映像为止。 好吧,那很好。 这是代码:
public async Task CreateChart(HttpMessage message)
{
var settings = new HighchartsSetting
{
ExportImageType = "png",
ImageWidth = 1500,
ServerAddress = "http://export.highcharts.com/"
};
var client = new HighchartsClient(settings);
if (message.Message == "Request was successfully")
{
// Get Chart Data
var results = getResults();
var chartOptions = new
{
title = new
{
text = "TestChart"
},
xAxis = new
{
categories = getDates();
},
series = new[]
{
new { data = getData() }
}
};
var link = await client.GetChartImageFromOptionsAsync(JsonConvert.SerializeObject(chartOptions));
string preLink = System.Text.Encoding.UTF8.GetString(link);
string highChartsLink = "http://export.highcharts.com/" + preLink;
byte[] file;
using (var downloadClient = new WebClient())
{
file = downloadClient.DownloadData(highChartsLink);
}
_chartFile = file;
}
如您所见,现在我的Image在_chartFile变量中为byte []格式。
现在我有了我的控制器:
public async Task<Image> GetRequest([FromBody]ChartRequestModel body)
{
....
// Creates Chart based on request
await highChart.CreateChart(message);
byte[] file = highChart.getChartFile();
using (Image image = Image.FromStream(new MemoryStream(file)))
{
return image;
}
}
因此,现在我将图像格式的图像返回到控制器。
我的客户收到来自控制器的信息。 这是代码(这是另一个应用程序):
IRestResponse response = client.Execute(requestCom);
所以现在我的问题是,客户端收到:response.content = System.Drawing.Bitmap但是我希望它接收位图图像,而不仅仅是它的类型。 我为客户使用RestSharp。
那么如何接收图像而不是数据类型呢?
感谢帮助
您是否尝试过对字节进行base64编码并将其作为参数发送给响应?
我将在Controller
上使用File
方法并返回ActionResult
。
public async Task<ActionResult> GetRequest([FromBody]ChartRequestModel body)
{
....
// Creates Chart based on request
await highChart.CreateChart(message);
byte[] file = highChart.getChartFile();
return File(file, "image/png"); //or image/jpg, etc.
}
现在,您将返回一个不是ActionResult
的对象,并且ASP.NET MVC默认情况下会返回ToString()
而不是ActionResult
的任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.