首页 > 解决方案 > 无法从 jquery 调用简单的 web api post 方法

问题描述

首先,我无法将模型从 jquery 传递到我的 web-api,所以我更改了代码并使用 GET 和 POST 编写了一个简单的控制器

using ContactInfo.Models;
using System.Collections.Generic;
using System.Linq;

using System.Web.Http;
using System.Web.Http.Cors;

namespace ContactInfo.Controllers
{
    [RoutePrefix("api/Contact")]
    public class ContactController : ApiController
    {
        List<ContactDto> contactList = new List<ContactDto>
       {
            new ContactDto { ContactId = 1, ContactName = "x", MobileNumber="1234567890" },
            new ContactDto { ContactId = 1, ContactName = "y", MobileNumber="1234567890" },
       };
        [HttpGet]
        [Route("GetProducts")]
        public IEnumerable<ContactDto> GetAllProducts()
        {
            return contactList;
        }
        [Route("AddProduct")]
        [HttpPost]
        public string Add(string name)
        {
            return name;
        }
    }
}

我的HTML如下

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>
    <!--<button id="Result" value="Submit" />-->
    <input id="Result" name="Result" type="button" value="Submit" />

    <script type="text/javascript">
        $(document).ready(function () {
            var name = 'hi';
            $("#Result").click(function () {
                $.ajax({
                    url: 'http://localhost:51856/api/Contact/AddProduct',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    type: 'POST',
                    data: name,
                    success: function (response) {
                        alert('hello');
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>

我在提交表单时遇到的错误如下

"Message":"未找到与请求 URI ' http://localhost:51856/api/Contact/AddProduct '匹配的 HTTP 资源。","MessageDetail":"在控制器 'Contact' 上找不到匹配的操作请求。"}

标签: c#jquery.netasp.net-web-api

解决方案


那么你做错了。有两种方法可以实现这一点。

  • 第一种方法 -

添加模型类 StudentModel.cs

public class StudentModel
{
    public string name { get; set; }
}

然后接受该参数作为模型 -

[Route("AddProduct")]
[HttpPost]
public string Add(StudentModel model)
{
    return "";
}

并在 Jquery 请求中->

var postData = {};
postData.name = "Tom";
$("#Result").click(function () {
            $.ajax({
                url: '/api/Contact/AddProduct,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: 'POST',
                data: JSON.stringify(postData),
                success: function (response) {
                    alert('hello');
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
  • 第二种方法->在 URl 中将名称作为参数传递,url: '/api/Contact/AddProduct?name=' + name并在 Action AddProduct 中将参数作为字符串接受(不推荐,因为它是 POST 请求)

推荐阅读