Model binding in ASP.NET Core to map underscores t

2020-08-09 09:19发布

问题:

I have a model class that I want to bind a query string to in my ASP.NET MVC Core (RC2) application.

I need to support underscores in query string keys to confirm to OAuth specs, but I want to work with title case property names in my application.

My model class looks like this:

class OauthParameters
{
    public string ClientId {get; set;}

    public string ResponseType {get; set;}

    public string RedirectUri {get; set;}
}

so I'd like to bind query strings like client_id, response_type and redirect_uri to it.

Is there a way for ASP.NET MVC Core to do this automagically or through an attribute annotation?

I've read some articles about writing custom model binders, but these seem to (1) be overly complex for what I'm trying to achieve and (2) are written for RC1 or earlier in mind and some of the syntax has changed.

Thanks in advance.

回答1:

You can use the FromQuery attribute's Name property here.

Example:

public class OauthParameters
{
    [FromQuery(Name = "client_id")]
    public string ClientId { get; set; }

    [FromQuery(Name = "response_type")]
    public string ResponseType { get; set; }

    [FromQuery(Name = "redirect_uri")]
    public string RedirectUri { get; set; }
}


回答2:

Solution for .net core 2.1 and 2.2

Or without attributes you can do something like this which is cleaner I think (of course if the model properties are same as query parameters).

Meanwhile I use it in .net core 2.1 and 2.2

public async Task<IActionResult> Get([FromQuery]ReportQueryModel queryModel) 
{ 

}