Required query string parameter in ASP.NET Core

前端 未结 5 1612
野性不改
野性不改 2020-12-18 22:11

Using ASP.NET Core 1.1 with VS2015 (sdk 1.0.0-preview2-003131), I have the following controller:

public class QueryParameters
{
    public int A { get; set;          


        
5条回答
  •  有刺的猬
    2020-12-18 22:53

    Let the framework do the work for you. Here is one solution, as it appears there are a number of ways to accomplish the same thing in ASP.NET Core. But this is what works for me and is quite simple. It seems to be a combination of some of the answers already given.

    public class QueryParameters
    {
        [Required]
        public int A { get; set; }
    
        public int B { get; set; }
    }
    
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        // [HttpGet] isn't needed as it is the default method, but ok to leave in
        // QueryParameters is injected here, the framework takes what is in your query string and does its best to match any parameters the action is looking for. In the case of QueryParameters, you have A and B properties, so those get matched up with the a and b query string parameters
        public IEnumerable Get(QueryParameters parameters)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(); // or whatever you want to do
            }
    
            return new [] { parameters.a.ToString(), parameters.b.ToString() };
        }        
    }
    

提交回复
热议问题