[英]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.