Model binding in ASP.NET Core to map underscores to title case property names

不羁岁月 提交于 2019-12-06 18:33:31

问题


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) 
{ 

}


来源:https://stackoverflow.com/questions/38305295/model-binding-in-asp-net-core-to-map-underscores-to-title-case-property-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!