在调用WebAPI时,调用方法主要有get和post,但参数传递需要注意几点,下面简单介绍一下ajax 调用时传参的几种方法:
- webapi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PostDemo.Controllers
{
[EnableCors(origins:"*",headers:"*",methods:"*")] //处理跨域访问
public class HomeController : ApiController
{
[HttpGet]
public string Get() {
return "Hello,This is Test!";
}
[HttpGet]
public string Get(string name) {
return $"This is parameter:{name} is input";
}
[HttpPost]
public JObject PostInfo(dynamic obj) { //动态类型类似于推断类型,客户端调用时需传入json格式字符串
//如data:JSON.stringify(obj),同时需要指定类型 contentType=application/json
string s1 = obj.name;
string s2 = obj.age;
return JObject.Parse("{\"name\":\"" + s1 + "\",\"age\":" + s2 + "}");
}
}
}
- 服务端解决跨域问题
- 安装 Micrsoft.AspNetWebApiCors
2.开启跨域配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Cors;
namespace PostDemo
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
config.EnableCors();
// Web API 路由
config.MapHttpAttributeRoutes();
config.Formatters.Clear(); //清除默认格式 xml
config.Formatters.Remove(config.Formatters.XmlFormatter); //删除xml格式
config.Formatters.Add(new JsonMediaTypeFormatter()); //增加JSON格式
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
- html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-1.10.2.js"></script>
<script>
function f1(){
$.ajax({
type:"get",
url:"http://localhost:58208/api/home",
data:{},
async:true,
success:function(res){
$("#txt").text(JSON.stringify(res));
},
error:function(err){
alert(JSON.stringify(err));
}
});
}
function f2(){
$.ajax({
type:"get",
url:"http://localhost:58208/api/home",
data:{"name":"张三"},
async:true,
success:function(res){
$("#txt").text(JSON.stringify(res));
},
error:function(err){
alert(JSON.stringify(err));
}
});
}
function f3() {
$.ajax({
type:"post",
url:"http://localhost:58208/api/home",
contentType:"application/json",
data:JSON.stringify({"name":"张三","age":12}),
async:true,
success:function(res){
$("#txt").text(JSON.stringify(res));
},
error:function(err){
alert(JSON.stringify(err));
}
});
}
</script>
</head>
<body>
<div>
<button onclick="f1()">测试1-Get无参</button>
<button onclick="f2()">测试2-Get有参</button>
<button onclick="f3()">测试3-Post动态参数</button>
</div>
<div>
<textarea id="txt" rows="25" cols="38" ></textarea>
</div>
</body>
</html>
- 效果