问题描述
我需要在请求中添加许多自定义标头.我可以用这样的东西
public ActionResult Get([FromHeader,必填] string header1,[FromHeader] string header2,...,[FromHeader] string headerx){......}
我不确定在一种方法中使用该数量的参数是否合适.我想使用这样的东西
公共类HeaderParameters{[必需的]公共字符串Header1 {get;放;}公共字符串Header2 {get;放;}...公共字符串Headerx {get;放;}}公共ActionResult Get([FromHeader] HeaderParameters headerParameters){......}
但这是行不通的.
如果我对HeaderParameters类的每个属性都使用[FromHeader]属性,则Swagger表现得很奇怪.
它就像一种魅力:
只需将 [FromHeader]
放在各处即可.也可以使用 [FromQuery]
.
I need to add many custom headers in my request. I can use something like this
public ActionResult Get([FromHeader, Required]string header1, [FromHeader]string header2, ... , [FromHeader]string headerx)
{
...
...
}
I am not sure if it is good to use that number of parameters in one method.I would like to use something like this
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)
{
...
...
}
But it doesn't work.
If I use [FromHeader] attribute for each property of HeaderParameters class Swagger is acting weird.
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"
}
There is an easier way in ASP.NET Core in .Net Core 3.1. Just put [FromHeader]
everywhere, like this:
[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();
}
And ForecastHeaders
look like this:
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; }
}
And when you send a request with Postman:
It works like a charm:
Just put [FromHeader]
everywhere. Work with [FromQuery]
as well.
这篇关于如何在Asp.Net Core 2.2中将[FromHeader]属性与自定义模型绑定一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!