Emily
Emily

Reputation: 187

BindRequired attribute for all parameters in an action

In a controller action when you add an attribute [BindRequired] to a parameter, it makes the parameter to be mandatory. But if you have multiple parameters, it gets extremely verbose. Is there a way to have something similar on the action level?

Upvotes: 1

Views: 2788

Answers (1)

Rena
Rena

Reputation: 36715

One way is to create a model and put all the parameters to the model like below:

public class Test
{
    [BindRequired]
    public string Id { get; set; }
    [BindRequired]
    public string Name { get; set; }
    //other property...
}

Controller:

public void Post([FromQuery] Test model)
{
     // return statement
}

Request url: https://localhost:portNumber/api/values?id=1&name=aa

Another way is to custom action filter like below:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var keylist = new string[] { "id", "name" };
        var keys = context.HttpContext.Request.Query.Keys;
        foreach(var item in keylist)
        {
            if(!keys.Contains(item))
            {
                context.ModelState.AddModelError(item, $"The {item} need to be provided");
            }
        }
        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(
                                                context.ModelState);
        }
    }

}

Controller:

[HttpPost]
[MyActionFilter]
public void Post(string id,string name)
{
    // return statement
}

Upvotes: 2

Related Questions