如何使用 Ajax 显示来自 BadRequest(message) 的字符串消息

How do I display the string message from BadRequest(message) using Ajax

我有我的 API 控制器

public ActionResult<Campaigns> AddCampaign([Bind("Name, Venue, AssignedTo, StartedOn, CompletedOn")] Campaigns campaigns)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (CampaignNameExists(campaigns.Name))
                {
                    throw new Exception("A campaign with that name already exists!");
                }
                if(!UsersIdExists(campaigns.AssignedTo))
                {
                    throw new Exception("User assigned to this Campaign does not exist!");
                }

                var isAdmin = _accessCheck.AdminCheck(campaigns.AssignedTo);

                //Check if user is Admin
                if(isAdmin.IsAdmin == 1)
                {
                    throw new Exception("Admins cannot be assigned to campaigns");
                }

                //Send User details to Repo for insertion to DB
                if (condition)
                    return result
                else
                    throw new Exception("Could not add campaign");
            }
            else
            {
                throw new Exception("Model State is not valid");
            }
        }
        catch (Exception ex)
        {
            var message = ex.Message;
            return BadRequest(message);
        }
    }

和我的观点

    <script>
    $(document).ready(function () {

        $("#createBtn").click(function () {
            let data = {
                "Name": $('#Name').val(),
                "Venue": $('#Venue').val(),
                "AssignedTo": $('#AssignedTo').val(),
                "StartedOn": $('#StartedOn').val(),
                "CompletedOn": $('#CompletedOn').val()                
            };
            $.ajax({
                type: "POST",
                url: "http://localhost:25733/api/Admin/Campaign/Add",
                data: JSON.stringify(data),
                contentType: "application/json",
                success: function () {
                    document.getElementById("campDivSuccess").style.display = 'block'
                },
                error: function (response) {
                    document.getElementById("campDivFail").style.display = 'block'
                    let fail = '<p>'+ response +'</p>'
                    $('#campDivFail').append(fail);
                }
            })
        })
    })
</script>

应该在此 div

中添加 BadRequest(string) 作为段落标记
<div class="alert alert-dismissible alert-danger" id="campDivFail" style="display: none">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>

它在做什么,但作为 [object] [Object] 而不是我分配给 BadRequest 的字符串,比如“无法分配广告系列”。我搜索了很多但找不到解决方案。我使用的响应错误吗?是否有其他功能可以执行此操作?

我找到了正确的文档。我在 'response' 中寻找的内容是“responseText”。我只需要在段落中使用 response.responseText。来源:developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest