Dev 404
Dev 404

Reputation: 1616

Can you use ModelBinding with a GET request?

I'm curious if it's possible to bind a query string that is passed in with a GET request to a Model.

For example, if the GET url was https://localhost:1234/Users/Get?age=30&status=created

Would it be possible on the GET action to bind the query parameters to a Model like the following:

[HttpGet]
public async Task<JsonResult> Get(UserFilter filter) 
{
    var age = filter.age;
    var status = filter.status;
}

public class UserFilter
{
    public int age { get; set; }
    public string status { get; set; }
}

I am currently using ASP.NET MVC and I have done quite a bit of searching but the only things I can find are related to ASP.NET Web API. They suggest using the [FromUri] attribute but that is not available in MVC.

Upvotes: 0

Views: 50

Answers (2)

guxxo
guxxo

Reputation: 86

You can can create an ActionFilterAttribute where you will parse the query parameters, and bind them to a model. And then you can decorate your controller method with that attribute. For example

 public class UserFilterAttribute : ActionFilterAttribute
{
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var controller = actionContext.ControllerContext.Controller as CustomApiController;
            var queryParams = actionContext.Request.GetQueryNameValuePairs();
            var ageParam = queryParams.SingleOrDefault(a => a.Key == "age");
            var statusParam = queryParams.SingleOrDefault(a => a.Key == "status");

            controller.UserFilter = new UserFilter { 
                                          Age = int.Parse(ageParam.Value),
                                          Status = statusParam.Value
                                          };
        }
}

The CustomApiController (inherits from your current controller) and has a UserFilter property so you can keep the value there. You can also add null checks in case some of the query parameters are not sent with the request..

Finally you can decorate your controller method

[HttpGet]
[UserFilter]
public async Task<JsonResult> Get() 
{
    var age = UserFilter.age;
    var status = UserFilter.status;
}

Upvotes: 0

Joel Fleischman
Joel Fleischman

Reputation: 434

I just tested the this, and it does work (at least in .net core 3.1)

[HttpGet("test")]
        public IActionResult TestException([FromQuery]Test test)
        {
            return Ok();
        }

        public class Test
        {
            public int Id { get; set; }
            public string Yes { get; set; }
        }

Upvotes: 1

Related Questions