1

I was trying to read the form url encoded body in ASP.net WebAPI. If the mapping is straight forward if the form variable and my model variable name is same (case insensitive), but if the names are different, the mapping fails.

For example,

POST /api/values HTTP/1.1
Host: localhost:62798
Accept: text/json
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 51ee1c5f-acbb-335b-35d9-d2b8e62abc74

uid=200&email=john%40jones.com&first_name=John&last_name=jones&phone=433-394-3324&city=Seattle&state_code=WA&zip=98105


public class SampleModel{
    public string UID { get; set; }    
    public string Email { get; set; }    
    public string FirstName { get; set; }    
    public string LastName { get; set; }    
    public string Phone { get; set; }    
    public string City { get; set; }    
    public string StateCode { get; set; }    
    public string Zip { get; set; }
}

Pay attention to first name, last name and state code variables. If the mode has first_name it will get mapped correctly. But if you want to adhere to C# naming conventions, we need to map first_name to FirstName.

I know if it were json, i could have easily mapped it with JSON Property name, but how can it be done with urlencoded form data?

Ref: ASP.net WebAPI Mapping with URL Encoded form

1 Answer 1

0

You should assign the alternative name using for binding Attribute in property definition like this:

public class SampleModel{
    public string UID { get; set; }    
    public string Email { get; set; }    

    [FromForm(Name = "first_name")]
    public string FirstName { get; set; }

    [FromForm(Name = "last_name")]
    public string LastName { get; set; }    
    public string Phone { get; set; }    
    public string City { get; set; }    

    [FromForm(Name = "state_code")]
    public string StateCode { get; set; }    
    public string Zip { get; set; }
}

Note that for form-urlencoded, you should use [FromForm] attribute before the arguments: [FromForm]string stateCode.

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.