我有一个 Angular 客户端,它向服务器发送 HttpRequest 以获取客户端信息:
getClient(roleId): Observable<ClientDto> {
let params = new HttpParams();
params = params.append('Id', clientId);
return this._httpClient.get<ClientDto>('myurl', {params});
}
在我的 Controller 上
[HttpGet]
public async Task<ActionResult<ClientDto>> GetClient(EntityDto<int> data)
{
return Ok(await clientsService.GetClient(data.Id));
}
public class EntityDto : EntityDto<int>, IEntityDto
{
public EntityDto()
{
}
public EntityDto(int id)
: base(id)
{
}
}
public class EntityDto<TKey> : IEntityDto<TKey>
{
[Required]
public TKey Id { get; set; }
public EntityDto()
{
}
public EntityDto(TKey id)
{
Id = id;
}
}
public interface IEntityDto : IEntityDto<int>
{
}
public interface IEntityDto<TKey>
{
/// <summary>
/// Id of the entity.
/// </summary>
TKey Id { get; set; }
}
当我从 Angular 进行调用时,我收到 Http 状态 415 响应 有谁知道为什么会发生这种情况吗?
最佳答案
我假设您正在使用 [ApiController]
,我认为您必须这样做才能看到您所描述的行为。使用此属性后,复杂类型的模型绑定(bind)规则将不同于默认规则。
就好像您指定了 [FromBody]
关于EntityDto<int>
属性(property)。当 [FromBody]
应用后,模型绑定(bind)过程会查看 Content-Type
随请求提供的 header 。在选择输入格式化程序时使用此 header 的值 - 在最简单的级别上,它将匹配例如application/json
到 JSON 输入格式化程序。如果 header 丢失或不包含受支持的值,则会发送 415 Unsupported Media Type 响应。
您已经知道解决方案,即使用绑定(bind)源属性覆盖推理:
public async Task<ActionResult<ClientDto>> GetClient([FromQuery] EntityDto<int> data)
我希望这个答案可以解释为什么需要这样做。
关于c# - Asp.Net httpGet 获取 httpstatus 415 用于调用具有复杂类型参数的 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58298670/