c#-从WebRequest显示图像
作者:互联网
我正在通过POST发出WebRequest,从Google Charts获取图像.
我遇到的问题是显示Google返回的图像.
我可以在Fiddler中看到发出了对图像的请求,并且在执行此操作时,图像在响应中返回:
var response = request.GetResponse();
但是从这里开始,我似乎无法从控制器输出图像.
这是我现在正在做的事情:
using (var dataStream = response.GetResponseStream())
{
if (dataStream == null) return;
using (var reader = new StreamReader(dataStream))
{
byte[] dataBytes = Encoding.UTF8.GetBytes(reader.ReadToEnd());
Response.ContentType = "image/png";
Response.BinaryWrite(dataBytes);
}
}
我的浏览器窗口中显示的错误消息是:
The image “[path to image]” cannot be displayed, because it contains
errors.
解决方法:
尝试使用WebClient,它将简化您的代码:
public ActionResult MyChart()
{
using (var client = new WebClient())
{
var data = client.DownloadData("http://......");
// TODO: the MIME type might need adjustment
return File(data, "image/png", "chart.png");
}
}
或者,如果您需要使用POST请求并发送一些值,请使用UploadValues方法:
public ActionResult MyChart()
{
using (var client = new WebClient())
{
var request = new NameValueCollection
{
{ "foo", "foo value" },
{ "bar", "bar value" },
};
var data = client.UploadValues("http://......", request);
// TODO: the MIME type might need adjustment
return File(data, "image/png", "chart.png");
}
}
然后在视图中:
<img src="@Url.Action("MyChart", "SomeController")" alt="chart" />
或者,如果url是静态的并且可以通过GET请求访问,则可以将其直接包含在视图中(在这种情况下,您无需执行控制器操作):
<img src="http://......" alt="chart" />
标签:c,asp-net-mvc,asp-net-mvc-3 来源: https://codeday.me/bug/20191208/2088219.html