gpt4 book ai didi

javascript - HttpDelete 和参数

转载 作者:行者123 更新时间:2023-11-30 11:37:49 25 4
gpt4 key购买 nike

创建了一个 ASP.NET Core Web API。使用以下代码,我可以使用 body 中的 Id 从 Postman 执行删除。

    [Authorize]
[Produces("application/json")]
[Route("api/Gigs")]
public class GigsController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private SignInManager<ApplicationUser> _signInManager;

public GigsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_context = context;
_userManager = userManager;
_signInManager = signInManager;
}


//[HttpDelete("{gigId}"]
[HttpDelete]
public IActionResult Cancel([FromBody] int gigId)
{
var userId = _userManager.GetUserId(User);

var gig = _context.Gigs.Single(g => g.Id == gigId && g.ArtistId == userId);
gig.IsCancelled = true;

_context.SaveChanges();

return Ok();

}

}

enter image description here

但是,当我使用以下 JS 代码通过我的网页执行它时,我收到 500 错误。传递正文的正确方法是什么?我也尝试过在没有 [FromBody] 和/或 [HttpDelete ("{gigId}")] 的情况下将其作为参数发送

    <script>
$(document).ready(function() {
$(".js-cancel-gig").click(function(e) {
var link = $(e.target);
if (confirm("Are you sure you want to delete this gig?")) {
$.ajax({
url: "/api/gigs/",
method: "DELETE",
contentType: "application/json",
data: JSON.stringify({ "gigId": link.attr("data-gig-id") }),
success: function() {
link.parents("li").fadeOut(function() {
$(this).remove();
});
},
error: function() {
alert("something failed");
}
});
}
});

});
</script>

最佳答案

在 Postman 中,您发送的是标量“3”,但在 JS 中,您发送的对象具有名为 gigId 的属性,其值为 3。您可能需要 data 采用表单数据格式,如 gigId=3 而不是使用 JSON。或者更改您的端点以接受具有名为 gigid 的属性的对象。

关于javascript - HttpDelete 和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com