ZUOXIANGE
ZUOXIANGE

Reputation: 61

How to use [FromBody] and [FromQuery] attribute at the same time?

In the post request,I need to get the parameters from the query string at the same time.This is my code,but can't work


 [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; }
    }

Upvotes: 5

Views: 4314

Answers (1)

Squirrelkiller
Squirrelkiller

Reputation: 2804

You have to put the different parameters in the method signature, so it would be something like

[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; }
}

bit depending on how your actual request looks like. This would read a Request-Object from the body, the id from the header and the traceId from the query.

Upvotes: 4

Related Questions