asp.net HttpPost返回错误

时间:2017-10-13 16:57:46

标签: c# asp.net ajax asp.net-web-api

使用ASP.NET Web API的我的HttpPost总是从AJAX请求中返回错误。

我的控制器:

public class ContactController : ApiController
{
    [HttpPost]
    [EnableCors(origins: "http://localhost:52884", headers: "*", methods: "*")]
    public string Post(myData m)
    {
        return String.Format("{0} {1:d}", m.FirstName, m.LastName);
    }
}

我的课程:

public class myData 
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

我的HTML请求:

    <html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
    <script>
        $.ajax(
        {
            url: "http://localhost:52884/api/contact",
            type: "POST",
            dataType: 'json',
            data: { FirstName: "FName", LastName: "LName" },
            success: function (result) {
                alert(result);
            },
            error: function (xhr, status, p3, p4) {
                var err = "Error " + " " + status + " " + p3;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).message;
                alert(err);
            }
        });
    </script>
</body>

</html>

当我在浏览器上运行它时,我收到警告:错误错误。

有谁知道我做错了什么?

如果我使用Postman运行它,它可以工作。但我需要在Ajax请求中,因为其他网站将调用我的API

2 个答案:

答案 0 :(得分:1)

我只是以这种方式重构你的代码:

[HttpPost]
[EnableCors(origins: "http://localhost:{port}", headers: "*", methods: "*")]
[Route("api/test")]
public string Post(myData model)
{
    return String.Format("{0} {1:d}", model.FirstName, model.LastName);
}

public class myData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

和Ajax电话:

<script>
    model = {
        FirstName: "FName",
        LastName: "LName"
    }

    $.ajax({
        url: "api/test",
        type: "POST",
        dataType: 'json',
        data: model,
        success: function(result) {
            alert(result);
        },
        error: function(xhr, status, p3, p4) {
            var err = "Error " + " " + status + " " + p3;
            if (xhr.responseText && xhr.responseText[0] == "{")
                err = JSON.parse(xhr.responseText).message;
            alert(err);
        }
    });
</script>

希望你能从中得到一个想法!

答案 1 :(得分:0)

它返回错误,因为ajax无法解析Post方法响应

        [HttpPost]
    [EnableCors(origins: "http://localhost:{port}", headers: "*", methods: "*")]
    [Route("api/test")]
    public string Post(myData m)
    {
        return string.Format("{{ \"FirstName\" : \"{0}\", \"LastName\" : \"{1}\" }}", m.FirstName, m.LastName);
    }