如何同时使用[FromBody]和[FromQuery]属性?

ZUO*_*NGE 5 .net c# asp.net .net-core asp.net-core

在post请求中,我需要同时从查询字符串中获取参数。这是我的代码,但无法工作


 [HttpPost("test")]
 public string Test(TestRequest request)
 {
      //TODO  ...
 }


    public class TestRequest
    {
        [FromHeader(Name = "id")]
        public string Id { get; set; }

        [FromQuery(Name = "traceId")]
        public string Trace { get; set; }

        public string Name { get; set; }

        [MaxLength(4)]
        public string Mark { get; set; }

        [Range(18, 35)]
        public int Age { get; set; }
    }

Run Code Online (Sandbox Code Playgroud)

Squ*_*ler 4

您必须将不同的参数放在方法签名中,所以它会是这样的

[HttpPost("test/{traceId}")] // Note the query parameter 
public string Test(
    [FromHeader(Name = "id")]string id,
    [FromQuery(Name = "traceId")]string trace,
    [FromBody]Request request
    )
{
    // TODO...
}

public class Request
{
    public string Name { get; set; }
    public string Mark { get; set; }
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

位取决于您的实际要求。这将从正文中读取请求对象,从标头中读取 id,从查询中读取 TraceId。