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

通过http.get传递字符串列表时遭遇Unsupported Media Type错误求助

解决Angular向C#传递字符串列表时的Unsupported Media Type错误

你当前把字符串列表转成JSON字符串作为单个参数传递的写法,会导致C#后端无法正确解析参数格式,进而触发Unsupported Media Type错误。下面给你几个实用的解决方案:

方案1:GET请求多参数传递数组(推荐)

直接把数组拆成多个同名的Query参数,不用JSON序列化,C#能直接识别:

Angular代码:

public GetIncomplete(companyId: number, locationCodes: string[]) {
  let params = new HttpParams().set('companyId', companyId.toString());
  
  // 给每个locationCode添加单独的参数
  locationCodes.forEach(code => {
    params = params.append('locationCodes', code);
  });

  return this.http.get<IvwStockTransfers>(`${this.URL}/get-incomplete`, { params });
}

C#后端对应Action:

[HttpGet("get-incomplete")]
public IActionResult GetIncomplete(int companyId, [FromQuery] string[] locationCodes)
{
    // 业务逻辑处理
    return Ok();
}

最终请求URL会是类似 /get-incomplete?companyId=123&locationCodes=CODE_A&locationCodes=CODE_B 的格式,C#能自动将同名参数解析为数组。

方案2:改用POST传递封装对象(适合长数组)

如果字符串列表很长,GET的URL长度可能受限,或者你更习惯用对象传参,可以改成POST请求:

Angular代码:

// 先定义参数类型
interface GetIncompleteParams {
  companyId: number;
  locationCodes: string[];
}

public GetIncomplete(companyId: number, locationCodes: string[]) {
  const requestBody: GetIncompleteParams = { companyId, locationCodes };
  return this.http.post<IvwStockTransfers>(`${this.URL}/get-incomplete`, requestBody);
}

C#后端定义请求模型并接收:

public class GetIncompleteRequest
{
    public int CompanyId { get; set; }
    public string[] LocationCodes { get; set; }
}

[HttpPost("get-incomplete")]
public IActionResult GetIncomplete([FromBody] GetIncompleteRequest request)
{
    // 业务逻辑处理
    return Ok();
}

这种方式参数结构清晰,也不会有URL长度限制的问题。

方案3:手动解析JSON字符串(不推荐)

如果一定要坚持原来的JSON序列化方式,C#后端需要手动反序列化这个字符串:

C#后端代码:

[HttpGet("get-incomplete")]
public IActionResult GetIncomplete(int companyId, string locationCodes)
{
    // 手动把JSON字符串转成数组
    var locationCodesArray = System.Text.Json.JsonSerializer.Deserialize<string[]>(locationCodes);
    // 业务逻辑处理
    return Ok();
}

不过这种方式容易因为JSON字符串的URL编码问题出bug,除非特殊情况不建议用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:55:17