当对后端API执行get请求时,我得到了415个不支持的媒体类型错误。在邮递员测试时,它工作得很好,但在角度上,我似乎无法使它工作。
角度
onExitSelectionChanged(event: MatSelectChange) {
this.getFare(this.selectedEntry, this.selectedExit);
}
getFare(A, B) {
var stations = new ComputeFareDTO();
stations.stationA = A;
stations.stationB = B;
this.getFareRequest(stations).subscribe(res => {
this.Fare = res;
})
}
getFareRequest(data: any): Observable<any> {
return this.http.get<any>(this.baseUrl + 'api/card/getFare', data);
}
class ComputeFareDTO implements IComputeFareDTO {
stationA: string;
stationB: string;
}
interface IComputeFareDTO {
stationA: string;
stationB: string;
}
C#
[Route("getFare")]
public decimal GetFareMrtTwo(ComputeFareDTO comp)
{
return GetFare(comp.StationA, comp.StationB);
}
public class ComputeFareDTO
{
public string StationA { get; set; }
public string StationB { get; set; }
}
}
它得到一个错误
获取本地主机:xxxxx/api/card/getFare 415 (不支持MediaType)
发布于 2021-03-25 07:55:59
除非另有规定,否则数据将使用Content-Type: application/x-www-form-urlencoded
发送。
要解决这个问题,请确保ASP.NET核心应用程序通过在dto声明(如public decimal GetFareMtrTwo([FromBody] ComputeFareDTO comp)
)之前添加[FromBody]
属性来接受public decimal GetFareMtrTwo([FromBody] ComputeFareDTO comp)
,并确保您的角度客户端以JSON的形式发送数据。
发布于 2021-03-25 08:05:34
这种类型的发送请求有两个错误:
编程错误,如果要向服务器发送一些数据,则应该以application/JSON正文类型发送数据。
2-概念错误:如果从服务器获取某些内容,并且需要发送一些可搜索的参数,则应该通过查询字符串或类似于GraphQL的方式发送它们。如果要向服务器发送一些数据,则应通过POST/PUT方法发送数据。
无论如何,您可以这样做:(但它在概念上是错误的,因为GET请求不应该有任何主体):
[HttpPost("getFare")]
public decimal GetFareMrtTwo([FromBody] ComputeFareDTO comp)
{
return GetFare(comp.StationA, comp.StationB);
}
你也可以像这一样发送你的帖子请求。
注意:您应该使用JSON.stringify方法以json格式发送您的正文。
第一个也是错误的解决方案是我上面说的话:\n。但最佳做法是采取以下步骤:
注意:在这个解决方案中,不需要将参数压缩为json <3。
注意:这里,您可以看到如何编写一个简单的模型绑定器。
玩得开心。
https://stackoverflow.com/questions/66795175
复制相似问题