OData Patch is not updating the database

asp.net-web-api c# entity-framework-6 odata patch

Question

I have a WebApi 2 controller. I want to use OData Patch on one of the controllers. Here's what I did so far.

I added the following line in WebApiConfig

config.MapODataServiceRoute("odata", "odata", GenerateEdmModle());
private static Microsoft.OData.Edm.IEdmModel GenerateEdmModle()
{
    var builder = new ODataConventionModelBuilder();
    builder.EntitySet<Auth>("Auths");

    return builder.GetEdmModel();
}

Then in the controller, This is how I'm trying to use patch method

[HttpPatch]
public async Task<IHttpActionResult> PatchAuth(int id, Delta<Auth> value)
{
    var auth = await db.Auth.FindAsync(id);
    if (auth == null) return NotFound();

    System.Diagnostics.Debug.WriteLine(auth.direction, auth.id);
    System.Diagnostics.Debug.WriteLine("Patching");

    try
    {
        value.Patch(auth);
        await db.SaveChangesAsync();
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.Message);
        return InternalServerError(e);
    }
    return Ok(value);
}

And here's how I'm sending it from angular service

// patch auth
service.patchAuth = function (authId, auth) {

    var request = $http({
        method: 'PATCH',
        url: baseUrl + 'api/Auths',
        data: JSON.stringify(auth),
        params: { id: authId },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });

    return (request.then(handleSuccess, handleError));
}

Here's what I see in Fiddler enter image description here

I see that the controller finds the Patch Method, and seems like it's trying to update, but the value never gets update.

I also add a breakpoint at value.Patch(auth) and checked the changedProperties, but there's nothing. I've been trying to find out what's causing this but haven't got a clue.

1
1
3/16/2017 7:31:50 PM

Accepted Answer

You specified application/x-www-form-urlencoded as your content type. Instead you have to use application/json.

When you specify application/x-www-form-urlencoded the call is still routed to the correct patch handler (as in your case), however no changed properties are passed into Delta<T> by Web.Api.

When you examine the raw HTTP Request in Fiddler your call should more look like this:

PATCH http://www.example.com/api/Auths(5) HTTP/1.1
Content-Type: application/json
Host: www.example.com
Content-Length: 20

{ "id" : 123456789 }
2
3/7/2017 5:01:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow