Net Core 2.1 Ajax Post 到控制器

Net Core 2.1 Ajax Post to Controller

一段时间以来我一直在纠结这个问题,就是看不出我做错了什么。

我在 SWAL 对话框中有一系列字段我想 post 到我的控制器但是对于我来说它不会,甚至不调用 Post 方法.收到的错误只是 400 错误代码。

var issue = JSON.stringify(this.swalForm);
        $.ajax({
            type: "POST",
            url: "../api/Issues",
            contentType: "application/json; charset=utf-8",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("RequestVerificationToken",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            dataType: "json",
            data: issue,
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);
            },
            success: function (msg) {
                console.log(msg.result);
            }
        });

那是我的 AJAX 电话

[HttpPost]
    public async Task<IActionResult> PostIssue([FromBody] Issue issue)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Issue.Add(issue);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetIssue", new { id = issue.Id }, issue);
    }

这是我控制器中的Post方法

public partial class Issue
{
    public Issue()
    {
        Document = new HashSet<Document>();
        IssueMember = new HashSet<IssueMember>();
    }

    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime? DueDate { get; set; }
    public int CategoryId { get; set; }
    public int StatusId { get; set; }
    public int? PriorityId { get; set; }
    public int ProjectId { get; set; }
    public string Location { get; set; }
    public int TeamId { get; set; }
    public DateTime CreatedDate { get; set; }
    public int CreatedById { get; set; }
    public DateTime? ModifiedDate { get; set; }
    public int? ModifiedById { get; set; }
    public bool Active { get; set; }

    public Category Category { get; set; }
    public User CreatedBy { get; set; }
    public User ModifiedBy { get; set; }
    public Priority Priority { get; set; }
    public Project Project { get; set; }
    public Status Status { get; set; }
    public Team Team { get; set; }
    public ICollection<Document> Document { get; set; }
    public ICollection<IssueMember> IssueMember { get; set; }
}

模特的样子

{"Title":"Ajax Issue","Description":"Made with ajax","DueDate":"2018-08-21","CategoryId":"3","StatusId":"2","PriorityId":"3","ProjectId":"1","Location":"Home","TeamId":"1","CreatedDate":"2018-08-21","CreatedById":"1","ModifiedDate":"2018-08-21","ModifiedById":"1","Active":"Active"}

最后是 Post

上的负载情况

想通了!! SMH...

Active 是我的控制器中的一个 bool 变量,但在检查时它向它传递了一个字符串 "Active"。 JSON 与模型不匹配,因此没有调用 api 方法。

检查您的负载并确保它与您的模型人物匹配!

Javascript 代码似乎没问题。第一次尝试使用 fiddler 或 postman 调试 web api 然后你会从 PostIssue() 方法而不是 500.

中得到准确的错误消息