c# - Asp.Net httpGet 获取 httpstatus 415 用于调用具有复杂类型参数的 Controller 方法

标签 c# angular asp.net-core .net-core

我有一个 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/

相关文章:

c# - 我们如何在 .net maui 7 中将单词包装在标签中

asp.net-core - 为什么默认的 mvc6 模板针对多个 DNX 版本?

c# - MVC Url.Content 与 javascript 局部变量

javascript - 使用 Karma 和 Jasmin 进行 Angular2 单元测试 SpyOn

angular - Ionic2/Cordova typescript 项目中的 Moment.js 插件

javascript - window.onload 在 Angular 4 中不起作用

c# - .NET Core 2.1 : AddHsts() and AddHttpsRedirection() not defined

asp.net-core - ASP.NET Core中的Windows身份验证: Manual login vs.自动Intranet登录和可用的组

c# - C# SortedList<TKey, TValue>.Keys.Contains 方法抛出 null 异常是一件好事吗?

c# - 从 xml 中读取属性