Asp.net WebAPI 构建后台数据接口

1.新建项目

2.选择WebApi,并使用空模板(这里不想要一些其他的mvc的东西)

3.新建一个model

4.写几个属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace APITest.Models
{
    public class Test
    {
        public int id { set; get; }
        public string name { set; get; }
    }
}

5.新增控制器

这里也用了空的控制器,避免多余代码干扰,其实后期可以写CodeSmith模板生成。

6.添加代码

using System.Collections.Generic;

using System.Linq;

using System.Web.Http;

using WebApplication3.Models;



namespace WebApplication3.Controllers

{

public class TestController : ApiController

{

Test[] products = new Test[]

{

new Test { id = 1, name = "Tomato Soup"},

new Test { id = 2, name = "Yo-yo" },

new Test { id = 3, name = "Hammer" }

};



public IEnumerable<Test> GetAllProducts()

{

return products;

}



public IHttpActionResult GetProduct(int id)

{

var product = products.FirstOrDefault((p) => p.id == id);

if (product == null)

{

return NotFound();

}

return Ok(product);

}



[HttpPost]

public IHttpActionResult PostTest([FromBody]Test t)

{

var product = products.FirstOrDefault((p) => p.id == t.id);

if (product == null)

{

return NotFound();

}

return Ok(product);

}

}

}

7.运行页面


这里注意路由规则,api/控制器名称/id

8. 增加下面两句,返回JSON格式的


其实就是修改Config的Formatter,使用JsonMediaTypeFormatter就好了。

设置WebApiConfig.cs后:





1. Post调用


当然也可以直接从Form中取值。例如:$(“#SearchForm”).serialize(),

2.能查询当然也能够进行增删改喽。

3. WebApi只有路由等基本框架,数据库操作完全可以自行选择,ADO.net, EF,nhibernate都可以。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小毅哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值