如何通过ASP.NET Core 2.2向API发出PATCH请求?

时间:2018-12-21 15:48:09

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.0 asp.net-core-2.2

我在ASP.NET Core 2.2的顶部有一个使用C#编写的应用程序。我创建了一个控制器,该控制器响应名为PATCH的{​​{1}}请求。这是我的控制器

Update

此外,要在未获得用户授权而不是重定向的情况下返回401错误,我向我的[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; } } 类添加了以下代码

Startup

现在使用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); } }; }); 调用此API,我做了以下

jQuery

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

如何正确处理此PATCH请求?

2 个答案:

答案 0 :(得分:3)

[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。

答案 1 :(得分:0)

您需要发送带有localhost:44313/api/Categories网址的请求。不要放置更新前缀。您只需要向您的localhost:44313/api/Categories端点发送补丁请求。

带有参数

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