Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 482
JamieNewman Avatar asked Jul 11 '16 11:07

JamieNewman


People also ask

Do you know what is model binding in asp net core How is it useful for developers?

Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.

What is model binding in asp net core MVC?

Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.

What is @model in asp net core?

The model classes represents domain-specific data and business logic in the MVC application. It represents the shape of the data as public properties and business logic as methods. In the ASP.NET MVC Application, all the Model classes must be created in the Model folder.


1 Answers

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; } } 
like image 173
Kiran Avatar answered Oct 08 '22 18:10

Kiran