7

I have a simple ApiController

public HttpResponseMessage Put(int orderid, [FromBody] Order order)
{
    // Do something useful with order.Notes here
}

and a class (the actual class contains several more properties)

public class Order
{
    public string Notes { get; set; }
}

and wish to handle PUT requests of the following type

PUT http://localhost/api/orders/{orderid}
Content-Type: application/x-www-form-urlencoded

notes=sometext

Everything works fine, but empty values are passed as null

notes=blah            // passes blah
notes=                // Passes null
someothervalue=blah   // Passes null

Is it possible to have ApiController distinguish between empty values and missing values?

1
  • Did you by any chance find a solution to this? Commented Jan 29, 2013 at 15:33

2 Answers 2

3

Have you tried annotating the property with DisplayFormatAttribute, like,

public class Order
{
    [DisplayFormat(ConvertEmptyStringToNull=false)]
    public string Notes { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked as perfectly. Rembember to add a reference to Assembly: System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll) and import the namespace. For full documentation see link
2

The root of this comes from the ReplaceEmptyStringWithNull that calls string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty

To fix this across your entire WebAPI project, you need to swap out the ModelMetadataProvider with one that sets the ConvertEmptyStringToNull to false

See Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false

This was actually "fixed" in v6 - see https://github.com/aspnet/Mvc/issues/3593

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.