Kural
Kural

Reputation: 212

ODataV4 patch always getting null value

I tried to get the values from the client to ODataV4 patch method. But it was unsuccessful. It always getting the null values from the client. Below is my code,

[HttpPatch]
    [EnableQuery]
    public IHttpActionResult Patch(int key, Delta<EmployeeDetail> patch)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var entity = _db.EmployeeDetails.Find(key);
        patch.Patch(entity);
        _db.SaveChanges();
        return Updated(entity);
    }

enter image description here

Upvotes: 1

Views: 477

Answers (1)

Chris Schaller
Chris Schaller

Reputation: 16669

Specification: OData Version 4.0. Part 1: Protocol Plus Errata 03
8.2.8.7 Preference return=representation and return=minimal
In OData, return=representation or return=minimal is defined for use with a POST, PUT, or PATCH Data Modification Request other than to a stream property, or to an Action Request.

If the Preference header is not present, return=minimal is assumed by default in the .Net implementation resulting in a 204 No Content response.

You should ensure that the client request has the Preference or Prefer header in the scenarios where you are expecting response data, or you can modify your patch handler to use an alternate default value:

[HttpPatch]
[EnableQuery]
public IHttpActionResult Patch(int key, Delta<EmployeeDetail> patch)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var entity = _db.EmployeeDetails.Find(key);
    patch.Patch(entity);
    _db.SaveChanges();


    // Return content by default
    // Disable this by sending in header { Prefer: "return=minimal" }
    if (!this.Request.Headers.Any(k => k.Key.Equals("prefer", StringComparison.OrdinalIgnoreCase) || k.Key.Equals("preference", StringComparison.OrdinalIgnoreCase)))
        this.Request.Headers.Add("Prefer", "return=representation");

    return Updated(entity);
}

NOTE: the Prefer header has not been hardcoded for all requests in this solution, only those requests that do not specify the header, in this way the user requests can still manipulate the response if you need to.

The values for Prefer are different in earlier versions of OData v3 and in the earlier versions of the .Net implementation of v4 in ODataLIb, you will find some documents that state the Prefer header needs a value of "content" or "return=content"... these solutions no longer work.

Upvotes: 1

Related Questions