且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

OData Patch不更新数据库

更新时间:2023-02-08 16:34:24

您指定了 application / x-www-form-urlencoded as您的内容类型。而您必须使用 application / json



当您指定 application / x- www-form-urlencoded 该调用仍然路由到正确的修补程序处理程序(如您的情况),但是没有更改的属性被传递到 Delta< T> by Web.Api。



当您检查Fiddler中的原始 HTTP请求时,您的通话应该更像:

  PATCH http://www.example.com/api/Auths(5)HTTP / 1.1 
内容类型:应用程序/ json
主机:www.example.com
内容长度:20

{id:123456789}
pre>

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.

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 }