2017-09-15 48 views
0

我有兩個C#應用程序。一個是服務另一個是客戶端。我的服務使用HighCharts.NET創建圖表。然後我將圖表發送到外部服務器,並將圖表作爲圖像。這種方法需要是異步的,因爲我必須等到我成爲服務器的映像。那麼,這工作正常。 下面是代碼:如何使用異步方法將C#中的圖像發送到客戶端

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; 
     } 

正如你看到的,現在我的形象是在_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。

那麼我怎樣才能接收圖像而不是數據類型?

感謝您的幫助

+0

你想返回'位圖圖像'所以改變你的返回類型爲'位圖' – esiprogrammer

+0

什麼框架的服務寫入? WCF? – Michael

+0

Asp.net MVC @Michael –

回答

1

我會在您的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默認返回的任何不是一個ActionResultToString()

+0

謝謝你的作品。我不知道它默認返回一個字符串。很高興知道 :) –

0

您是否嘗試過編碼的字節數和發送,在作爲參數的響應的base64?

相關問題