Web API(RESTful)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caishu1995/article/details/82978463

特性

    一个构建基于restful服务的理想平台。

    基于Asp.Net,支持ASP.Net 请求/响应管道

    有良好的路由机制。

    支持不同格式的响应数据。

    包括新的HttpClient。

创建空的工程

1、创建一个空的web工程 ASP.NET Web应用程序

2、右键-管理NuGet程序包-搜索"web api"-安装

3、创建App_Start文件-创建类-更名为APIConfig-在类里写入如下代码

public static void Register(HttpConfiguration config)
{
    // Web API routes
    config.MapHttpAttributeRoutes();
​

    //config.Routes是一个集合,MapHttpRoute()在内部创建一个IHttpRoute实例,并将其添加到集合中。
    config.Routes.MapHttpRoute(
        name: "DefaultApi",//路由名称,DefaultApi可以更改,但禁止重复
        routeTemplate: "AA/{controller}/{id}",//AA可以更改
        defaults: new { id = RouteParameter.Optional }
    );
}

4、创建全局应用程序类-在Application_Start里写入如下代码

GlobalConfiguration.Configure(APIConfig.Register);//APIConfig是刚才的类名,Register是方法名

5、创建Controller文件-创建Web API控制器-更名为indexController-在类里写入如下代码

// GET AA/index
public string Get(){ return "value"; }

​
// GET AA/index?id=1
public string Get(string id){ return id; }


// POST AA/index
public void Post([FromBody]string value){}

​
// PUT AA/index?id=1
public void Put(int id, [FromBody]string value){}


// DELETE AA/index?id=1
public void Delete(int id){}

6、创建一个页面,用ajax请求路径就可以了。

细节理解

//注意:如果想通过Get请求AA/index/names,可以在Get前面加Route。
//     则请求的时候,如果路径是AA/index/names,则进入以下函数
[Route("AA/index/names")]
public string Get(){ return "value"; }

    刚才看到了[FromBody]不知道是干什么的,那我们先来看看参数的绑定的默认规则。默认情况下,Web API从查询字符串中得到基本类型参数的值,从请求主体中得到复杂类型参数的值。

HTTP方法 Query string Request Body
Get 简单类型、复杂类型
Post 简单类型 复杂类型
PUT 简单类型 复杂类型
PATCH 简单类型 复杂类型
DELETE 简单类型、复杂类型

注:默认Post方法不能包含多个复杂类型的参数,因为最多允许一个参数读取请求主体中的数据。

    如果我们要改变这种状况,可以使用[FromUri]属性,从查询字符串中获取复杂类型的值;使用[FromBody]属性,从主体获取原始类型的值。

    返回值刚才见过void 和 简单类型或复杂类型。其实还有两种复杂的:HttpResponseMessage类型 和 IHttpActionResult类型
 

参考:

    http://www.yuanjiaocheng.net/webapi/first.html  Web API教程

猜你喜欢

转载自blog.csdn.net/caishu1995/article/details/82978463