使用图像内容返回HTTP错误状态代码

时间:2017-07-24 09:07:43

标签: asp.net-web-api http-status-codes

我正在处理将返回图片的API。如果在API中遇到任何错误,虽然我可以发出带有文本内容或根本没有内容的HTTP-500响应(或类似的错误代码),但我需要能够返回一个带有内部错误的图像内容。形象本身。换句话说,当遇到任何错误时,我创建错误文本的图像表示并返回图像,http状态代码为500 - 内部服务器错误。我使用的是ASP.net Web API,我能够使用图像内容和mime类型创建HTTP 500响应,作为" image / jpg"。

Http 500,纯文字回复:

HTTP/1.1 500 Internal Server Error
Content-Length: 14
Content-Type: text/plain; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 24 Jul 2017 06:43:55 GMT

Error Occured!

Http 500 with Image Content:

HTTP/1.1 500 Internal Server Error
Content-Length: 622485
Content-Type: image/jpg
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 24 Jul 2017 06:44:56 GMT


<<ImageContent>>

虽然有可能,但我需要知道这种方法是否符合Web API的最佳实践。感谢。

2 个答案:

答案 0 :(得分:0)

最好的做法(“每个人都这样做”)是返回带有Content-Type: text/html的HTML,即使请求是要获取图像。

答案 1 :(得分:-1)

您可以访问此网站here

下面,您可以查看共享链接中的代码:

var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

return result;
相关问题