1.WebAPI添加类库引用
2.WebApiConfig添加
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
3.控制器示例
namespace WebApiTest.Controllers
{
[EnableCors("*", "*", "*")]
public class UserModelsController : ApiController
{
// GET: api/UserModels
public List<UserModels> Get()
{
return new List<UserModels>() { new UserModels() {Id=1,Name="小红",EmailAddress="1111@qq.com" } };
}
// GET: api/UserModels/5
public string Get(int id)
{
return "value";
}
public string Post([FromBody]UserModels value)
{
return value.Name;
}
// PUT: api/UserModels/5
public string Put(int id, [FromBody]UserModels value)
{
return "你好" + id + "," + value.Name;
}
// DELETE: api/UserModels/5
public void Delete(int id)
{
}
}
}
4.示例1:Ajax调用PUT
$.ajax({
url: "http://localhost:30172/api/UserModels/12",
data: { "Name": "SSSSSSS" },
type: "Put",
success: function (data) {
$('#content').html(data);
alert(data);
}
});
示例2:HTML页面调用
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/jquery-1.12.0.min.js"></script>
</head>
<body>
<form id="form1" action="http://localhost:30172/Api/UserModels" method="post">
<input name="Name" id="Name"/>
<input name="EmailAddress"/>
<button>提交</button>
</form>
</body>
</html>