Adam Parker
Adam Parker

Reputation: 156

Web Api 2 - FromBody object always null when a variable contains ampersand

I have an endpoint specified that reads the request body using [FromBody], but, the value is always null when one of the fields contains an ampersand (&). The client in question is passing XML to the endpoint.

public IHttpActionResult CreateStage([FromBody] JobStageWrapper stage)

The JobStageWrapper object

public class JobStageWrapper
{
    public JobStage job { get; set; }
}

The Stage object

public class JobStage
    {
        public string jobno { get; set; }
        // Job Stage
        public string jobStage { get; set; }
        // Stage Date
        public DateTime StageDate { get; set; }
        public string Memo { get; set; }
    }

So, for example:

<memo>My name is Adam & I live in England</memo> 

Returns null

<memo>My name is Adam and I live in England</memo>

Returns a populated object

Is there a way I can intercept the request body to replace these special characters so that the object is always fully populated?

Thanks!
Adam

Upvotes: 1

Views: 327

Answers (1)

Igor
Igor

Reputation: 62213

... one of the fields contains an ampersand (&). The client in question is passing XML to the endpoint.

The client should make sure that the xml is escaped. Ampersand should be passed as &amp;

This is not a valid xml element

<memo>My name is Adam & I live in England</memo> 

but this is

<memo>My name is Adam &amp; I live in England</memo> 

See List of XML and HTML character entity references -> Predefined entities in XML section for a list of special characters in XML that need to be escaped.

Or here is the list copied from this previous answer on SO What characters do I need to escape in XML documents?.

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

Upvotes: 1

Related Questions