HttpDelete和参数

时间:2017-05-02 00:08:44

标签: javascript json asp.net-web-api asp.net-core

创建了一个ASP.NET Core Web API。使用以下代码,我可以使用身份中的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(&#34; {gigId}&#34;)]

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

1 个答案:

答案 0 :(得分:3)

在邮递员中你发送一个标量“3”但是在JS中你发送的对象的属性名为gigId,其值为3.你可能希望data在表单数据格式,如gigId=3,而不是使用JSON。或者更改端点以接受具有名为gigid的属性的对象。