c# - 无法从 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' 上找不到匹配的操作请求。"}
解决方案
那么你做错了。有两种方法可以实现这一点。
- 第一种方法 -
添加模型类 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 请求)
推荐阅读
- javascript - UseState 来控制
- javascript - 2021 年适用于包括 safari 在内的所有浏览器的 pwa javascript 视频录制应用程序
- javascript - 如何在 json 中创建正确的 html 标签
- javascript - 当我有一个不区分大小写的动态变量时如何使用 match() 方法?
- python - 以 10 为基数的 int() 的无效文字:'nan' 在尝试替换 NaN 中的 0 时
- python - 使用 seleniumrequests 在站点上实现自动化
- data-structures - 检测由链表表示的图中3个相邻顶点的循环
- python - 如何将两个文件读入字典并打印特定值
- flutter - 错误状态字段在 DocumentSnapshotPlatform 中不存在不到一秒
- android - 由于现有相机用户(代码 7),相机“0”的手电筒不可用