首页 > Windows开发 > 详细

Asp.Net WebApi Get请求说明(一)

时间:2017-02-03 14:32:49      阅读:185      评论:0      收藏:0      [点我收藏+]

Asp.Net WebApi+JQuery Ajax的Get请求整理

一、总结

1.Asp.Net WebApi默认不支持Get请求,需要在Action方法上指定[HttpGet]
2.默认路由中,没有指定action,如果想路由到action不要手动指定
3.WebApi返回值的json对象,使用$.get 接收返回值,不需要手动反序列化处理
4.WebApi的Get请求中,Action可以接收多个参数

二、代码验证说明

1.默认不支持Get请求,需要在Action上指定请求类型[HttpGet]

[HttpGet]
public string ShowName(string name)
{
    return $"您传入的名字:‘{name}’";
}

异常内容:

技术分享

2.默认路由中没有action参数处理

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints:new {id=@"\d+" }
);

可以手动添加处理

config.Routes.MapHttpRoute(
    name: "DefaultApi2",
    routeTemplate: "api/{controller}/{action}",
    defaults: new { action = "Index" }
);

3.WebApi的返回值都是json数据类型,JQuery中的Ajax会自动识别为json对象,不需要手动反序列化

[HttpGet]
public object ShowName3(string name, int age)
{
    return new { name = name, age = age, success = true };
}

相应结果:

技术分享

技术分享

返回字典类型:

[HttpGet]
public Dictionary<string, string> GetList1(bool IsShow)
{
    Dictionary<string, string> dict = new Dictionary<string, string>();
    if (IsShow)
    {
        dict.Add("name1", "张三");
        dict.Add("name2", "李四");
    }
    return dict;
}

JavaScript代码:

$.get(/api/user/getlist1, {
    isshow: true
}, function (data) {
    console.info(data);
    alert(data);
});
$.get(/api/user/showname2, {
    name: 张三丰,
    age:19
}, function (data) {
    console.info(data);
    alert(data);
});

更多:

Asp.Net WebAPI Get提交、Post提交处理

使Asp.net WebApi支持JSONP和Cors跨域访问

Asp.Net WebApi Get请求说明(一)

原文:http://www.cnblogs.com/tianma3798/p/6362500.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!