2

I'm trying to bind a single parameter of a URL query to a single property in an action method.

The URL is along the lines of:

/user/validate?Some.Prefix.Username=MyUserName

And my controller and action method are along the lines of:

public class UserController : Controller
{
    public IActionResult Validate([Bind(Prefix = "Some.Prefix")]string username)
    {
        return Ok(username);
    }
}

However the username parameter is always null when this action method is called. It seems this is a result of using the BindAttribute with a string parameter, rather than a simple class parameter. If I replace the string username parameter with a simple class containing a Username property, I can capture the value as expected.

public class UserController : Controller
{
    public IActionResult Validate([Bind(Prefix = "Some.Prefix")]ValidationModel model)
    {
        return Ok(model);
    }
}

public class ValidationModel
{
    public string Username { get; set; }
}

Is there any way to bind to a single parameter (rather than a class parameter) when the URL parameter name contains prefixes?

1 Answer 1

3

For simple types like int and string, the Bind Prefix overrides the model name for the parameters. Using your action method as an example, the DefaultModelBinder would be looking for the name "Some.Prefix" instead of "username".

So, if you want to work around this and not require a complex type, you need to specify the fully qualified name.

public IActionResult Validate([Bind(Prefix = "Some.Prefix.Username")]string username)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.