[英]C# WebAPI redirect to a Link that displays an Image
public HttpResponseMessage getLogoPath(int ID)
{
String urlsubfix = dataManager.getMobileLogoPath(ID);
String urlToReturn = PictureController.urlprefix +urlsubfix;
var response = Request.CreateResponse(HttpStatusCode.Redirect);
response.Headers.Location = new Uri(urlToReturn);
return response;
}
我想要一个API调用来返回图像,我如何做到这一点是重定向到另一个具有该图像的链接,例如:
http://steve.files.wordpress.com/2006/03/Matrix%20tut%202.jpg
我正在尝试使用PostMan对此进行测试,这给了我一个破碎的图像。 我尝试绕行,但仍然找不到解决方案。
-----编辑需要此代码的一部分
public HttpResponseMessage GetCustomerBarCodeLogo(String ID)
{
Barcode BC = new Barcode();
Image img =BC.Encode(TYPE.CODE128, "123456789");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(img, typeof(byte[]));
MemoryStream dataStream = new MemoryStream(resourceByteArray);
result.Content = new StreamContent(dataStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
这将返回损坏的图像。
------最新更新
我发现了问题所在。 发生的情况是SSL基本身份验证存在问题。 发生的情况是,当客户端第一次希望传递请求时,身份验证已正确设置。 但是,当它尝试获取由内部代码触发的另一个请求的图像时,该请求没有autherizationHeader且未经身份验证。 我不知道第二个事件在哪里触发,所以我不知道如何手动设置该标头。
您无法重定向以响应此URL中的图像,您的呼叫者将能够更改位置。
第一种解决方案,请尝试直接将图像结果用于Web API,例如:
public HttpResponseMessage getLogoPath(int id)
{
string pathImage = // a way to get the imagem path..
// create response
HttpResponseMessage response = new HttpResponseMessage();
// set the content (image)
response.Content = new StreamContent(new FileStream(pathImage));
// set the content type for the respective image
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); // or jpg, gif..
return response;
}
或将已移动状态代码用于smaple:
public HttpResponseMessage getLogoPath(int ID)
{
String urlsubfix = dataManager.getMobileLogoPath(ID);
String urlToReturn = PictureController.urlprefix + urlsubfix;
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri(urlToReturn);
return response;
}
这是一种可能适合您的替代方法。 这是我使用的技巧的结尾。
public HttpResponseMessage GetCustomerBarCodeLogo(String ID)
{
Barcode BC = new Barcode();
Image img =BC.Encode(TYPE.CODE128, "123456789");
var dataStream = new MemoryStream();
img.Save(dataStream, ImageFormat.Png);
dataStream.Position = 0;
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(dataStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
您可以使用FileResult为例
public FileResult GetLogo(string imageName)
{
return File(Server.MapPath("~/App_Data/Images/") + imageName, "image");
}
在这种情况下,文件功能采用文件路径和内容类型并返回文件响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.