You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用返回图片的C# Web API遇Http解析失败问题

问题与解决方案:C# Web API返回图片接口在Angular调用时解析失败

问题描述

C# Web API端编写了返回图片的Post接口,Angular调用时控制台报错:

Http failure during parsing for https://localhost:44476/library/getimage

原API代码(C#)

[HttpPost]
[Route("GetImage")]
[ValidateAntiForgeryToken]
public FileResult GetImage(string name)
{
    if (string.IsNullOrEmpty(name)) {
        return File("imgs/nodisponible.jpg", "image/jpg");
    }
    var imagen = REST.GetImage(name);
    return new FileContentResult(imagen, "image/jpeg");
}

原Angular调用代码

getimage(word: any): Observable<any> {
  return this.http.post<ArrayBuffer>(this.baseUrl + 'library/getimage', word, {
    headers: this.headers,
    withCredentials: true,
  });
}

原图片展示代码

const iname = JSON.stringify(this.consultadetalle?.cover_url);
this.dataService.getimage(iname).subscribe((responses) => {
  $('#imagencover').attr('src', "data:image/png;base64," + responses);
});

解决方案

1. Angular请求端修改:指定响应类型为Blob

错误核心是Angular默认会将响应解析为JSON,但接口返回的是二进制图片数据,导致解析失败。需在请求配置中明确responseType为'blob':

getimage(word: string): Observable<Blob> {
  return this.http.post<Blob>(this.baseUrl + 'library/getimage', word, {
    headers: this.headers,
    withCredentials: true,
    responseType: 'blob' as 'json' // 类型断言避免TS类型报错
  });
}

2. 图片展示逻辑修改

获取到Blob后,使用URL.createObjectURL生成可直接用于img标签的链接(比base64转换更高效):

const iname = this.consultadetalle?.cover_url; // 无需JSON.stringify,直接传入字符串即可
this.dataService.getimage(iname).subscribe((response) => {
  const imageUrl = URL.createObjectURL(response);
  $('#imagencover').attr('src', imageUrl);
  // 组件销毁时记得释放URL,避免内存泄漏
  // this.destroy$.pipe(take(1)).subscribe(() => URL.revokeObjectURL(imageUrl));
});

3. C# Web API端检查项

  • 路由匹配:确保控制器类上有[Route("library")]属性,否则Angular调用的library/getimage会找不到接口。
  • 防伪令牌:如果Angular未配置传递XSRF令牌,[ValidateAntiForgeryToken]会导致400错误,测试阶段可暂时注释该属性,后续再配置Angular的XSRF防护。
  • 字节数组有效性:确认REST.GetImage(name)返回的是正确的图片字节数组,可临时将接口改为HttpGet,直接访问接口地址验证图片是否能正常返回。

内容的提问来源于stack exchange,提问作者Leandro Bardelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:36:16