OData Patch is not updating the database

£可爱£侵袭症+ 提交于 2019-12-24 07:37:52

问题


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

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:


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 }


来源:https://stackoverflow.com/questions/42237043/odata-patch-is-not-updating-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!