如何使用 ASP.NET Core 2.2 向 am API 发出 PATCH 请求?

How to make a PATCH request to am API with ASP.NET Core 2.2?

我有一个在 ASP.NET Core 2.2 之上使用 C# 编写的应用程序。我创建了一个控制器来响应名为 UpdatePATCH 请求。这是我的控制器

[Route("api/[controller]"), ApiController, Produces("application/json")]
public class CategoriesController : ControllerBase
{
    [HttpPatch("{propertyId}/{listId}/{isOn}"), Authorize]
    public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
    {
        // Do something
        return true;
    }
}

此外,为了 return 当用户未被授权而不是重定向时出现 401 错误,我将以下代码添加到我的 Startup class

services.ConfigureApplicationCookie(config =>
{
    config.Events = new CookieAuthenticationEvents
    {
        OnRedirectToLogin = ctx =>
        {
            if (ctx.Request.Path.StartsWithSegments("/api", StringComparison.CurrentCultureIgnoreCase))
            {
                ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                ctx.Response.Redirect(ctx.RedirectUri);
            }

            return Task.FromResult(0);
        }
    };
});

现在使用 jQuery 调用此 API 我做了以下操作

$('.update-property').click(function (e) {
    e.preventDefault();
    var obj = $(this);
    $.ajax({
        url: '/api/Categories/Update',
        type: 'PATCH',
        data: {
            'propertyId': obj.data('property-id'),
            'listId': obj.data('list-id'),
            'isOn': obj.data('is-on') === 'True' ? 'false' : 'true'
        },

        success: function (response) {

            console.log(response);

            // if response unauthorized, redirect to the login page with the ReturnUrl
            // else if response.data is true then change the icon
        }
    });
});

但此请求保持 returning 404 http 错误代码。我在开发人员工具中检查了这个问题,发现参数设置正确并且 URL 有效。

如何正确处理这个 PATCH 请求?

您需要使用 localhost:44313/api/Categories url 发送请求。不要放置更新前缀。您只需要将补丁请求发送到您的 localhost:44313/api/Categories 端点。

带参数

localhost:44313/api/Categories/{propertyId}/{listId}/{isOn}

[Route("api/[controller]"), ApiController, Produces("application/json")]
public class CategoriesController : ControllerBase
{
    [HttpPatch("{propertyId}/{listId}/{isOn}"), Authorize]
    public ActionResult<bool> Update(int propertyId, int listId, bool isOn)

此处的路由模板决定了您的更新端点的 URL。在这种情况下,生成的 URL 模板将是这样的:

api/Categories/{propertyId}/{listId}/{isOn}

例如,此端点的有效 URL 将是 /api/Categories/12/34/true

如果您不想将值作为参数传递(因为您已经在正文中传递了它们),则必须更改路由模板。例如,您可以只删除操作方法上的路由模板:

[HttpPatch, Authorize]
public ActionResult<bool> Update(int propertyId, int listId, bool isOn)
// …

那么,URL 就是 api/Categories

当然,您也可以将api/Categories/Update作为端点的URL,但是对于REST,通常不建议在URL中包含方法名称。 PATCH 请求通常意味着“更新此资源”,然后您将指向资源的 URL。