c# - 如何在 Asp.Net Core 2.2 中将 [FromHeader] 属性与自定义模型绑定(bind)一起使用

标签 c# asp.net-web-api

我需要在我的请求中添加许多自定义 header 。我可以使用这样的东西

public ActionResult Get([FromHeader, Required]string header1, [FromHeader]string  header2, ... , [FromHeader]string headerx)
{
...
...
}

我不确定在一种方法中使用这么多参数是否好。
我想用这样的东西
public class HeaderParameters 
{
  [Required]
  public string Header1 { get; set; }
  public string Header2 { get; set; }
  ...
  public string Headerx { get; set; }
}

public ActionResult Get([FromHeader]HeaderParameters headerParameters)
{
  ...
  ...
}

但它不起作用。

如果我对 HeaderParameters 类的每个属性使用 [FromHeader] 属性,Swagger 就会表现得很奇怪。

Request example http://prntscr.com/p14kd7
{
  "errors": {
    "Device": [
      "The Header1 field is required."
    ]
  },
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "0HLPG9SNNJ1U2:00000001"
}

最佳答案

在 .Net Core 3.1 中的 ASP.NET Core 中有一种更简单的方法。就放[FromHeader]到处都是,像这样:

[HttpPost("multipleHeaders")]
public IActionResult Post([FromHeader] ForecastHeaders forecastHeaders)
{
    try
    {
        Console.WriteLine($"Got a forecast for city: {forecastHeaders.City}," +
                            $"temperature: {forecastHeaders.TemperatureC} and" +
                            $"description: {forecastHeaders.Description}!");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        return StatusCode(StatusCodes.Status500InternalServerError);
    }

    return new AcceptedResult();
}
ForecastHeaders看起来像这样:
public class ForecastHeaders
{
    [FromHeader]
    public string City { get; set; }

    [FromHeader]
    public int TemperatureC { get; set; }

    [FromHeader]
    public string Description { get; set; }

    [FromQuery]
    public string Sorting { get; set; }
}
当您向 Postman 发送请求时:
enter image description here
它就像一个魅力:
enter image description here
就放[FromHeader]到处。与 [FromQuery] 合作也是。

关于c# - 如何在 Asp.Net Core 2.2 中将 [FromHeader] 属性与自定义模型绑定(bind)一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57768912/

相关文章:

c# - Entity Framework - 生成类

c# - 防伪 token Web Api 2

c# - 同一个 HttpVerb 的多个操作

c# - 如何在 ASP.NET Web API 中设置下载文件名

c# - 如何将 HttpResponseMessage 内容读取为文本

json - AngularJS、MVC4、Web API、Json 反序列化 $ref

c# - MVC 4 GeneratePasswordResetToken 如何生成一个新的?

c# - 错误 "An unhandled exception of type ' System.IO.IOException' 出现在 mscorlib.dll 中”

c# - 声明变量 - 最佳实践

c# - 我的 PDF 字体名称中的额外字符是什么?