无法从客户端脚本调用API

时间:2018-10-29 01:01:18

标签: jquery ajax asp.net-mvc

我编写了以下代码,用于从客户端脚本调用API。

Cshtml

<button class="btn btn-link btn-sm js-toggleFollowing" data-user-id="@gig.ArtistId">Follow</button>

API调用:

$(".js-toggleFollowing").click(function (e)
{
    var button = (e.target);

    $.post("/api/followings", { followeeId: button.attr("data-user-id") })
    .done(function ()
    {
        button.text("Following");
    })
    .fail(function ()
    {
        alert("Something failed");
    })
});

API控制器方法

// Code for api call

[HttpPost]
public IHttpActionResult Follow(FollowingDto dto)
{
    var userId = User.Identity.GetUserId();

    if (_context.Followings.Any(f => f.FolloweeId == userId && f.FolloweeId == dto.FolloweeId.ToString()))
        return BadRequest("The Following alreday exists.");

    var following = new Following
    {
        FollowerId = dto.FolloweeId.ToString(),
        FolloweeId = userId
    };

    _context.Followings.Add(following);
    _context.SaveChanges();

    return Ok();
}

DTO类:

public class FollowingDto
{
    public int FolloweeId { get; set; }
}

API调用与邮递员一起工作,而没有将参数转换为DTO。但是当我使用dto作为参数时它不起作用。 dto类也被复制。

请帮助我解决此问题。

0 个答案:

没有答案
相关问题