C# 编写Web API

1)创建Web API项目

打开VS2012->FILE->New->Project->Web->ASP.NET MVC 4 Web Application, 修改名字为WebAPIApplication, 单击OK, 在Project Template中选择Web API,单击OK.



2)添加Controller Template选择Empty API controller名字为StudentValueController.cs代码如下

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

namespace MvcApplication22.Controllers
{
    public class StudentValueController : ApiController
    {
        /// <summary>  
        /// 根据搜索条件获取学生信息  
        /// GET /api/StudentValue/GetStudents?stuName=chad&stuAddress=jiaxing  
        /// </summary>  
        /// <param name="name">姓名</param>  
        /// <param name="address">地址</param>  
        /// <returns>满足条件的学生信息</returns>  
        [HttpGet]
        public IEnumerable<StudentInfo> GetStudents(string stuName, string stuAddress)
        {
            using (DataClassesDataContext dcdc = new DataClassesDataContext())
            {
                List<StudentInfo> items = dcdc.StudentInfos.ToList();
                if (stuName != null)
                {
                    items = items
                        .Where(u => u.stuName.Contains(stuName)).ToList();
                }
                if (stuAddress != null)
                {
                    items = items
                        .Where(u => u.stuAddress.Contains(stuAddress)).ToList();
                }
                return items;
            }
        }
        /// <summary>  
        /// 根据学生编号获取学生信息  
        /// GET /api/StudentValue/GetStudentById/{id}  
        /// </summary>  
        /// <param name="id">编号</param>  
        /// <returns>学生信息</returns>  
        [HttpGet]
        public StudentInfo GetStudentById(int id)
        {
            using (DataClassesDataContext dcdc = new DataClassesDataContext())
            {
                return dcdc.StudentInfos
                    .FirstOrDefault(u => u.stuId.Equals(id));
            }
        }
        /// <summary>  
        /// 添加学生信息  
        /// POST /api/StudentValue/AddStudent  
        /// {stuName:'jack', stuAddress:'jiangsu'}  
        /// </summary>  
        /// <param name="item">学生信息</param>  
        /// <returns>添加成功返回学生信息, 否则返回null</returns>  
        [HttpPost]
        public StudentInfo AddStudent(StudentInfo item)
        {
            try
            {
                using (DataClassesDataContext dcdc = new DataClassesDataContext())
                {
                    dcdc.StudentInfos.InsertOnSubmit(item);
                    dcdc.SubmitChanges();
                    return item;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>  
        /// 修改学生信息  
        /// PUT /api/StudentValue/UpdateStudent/{id}  
        /// {stuName:'jack', stuAddress:'jiangsu'}  
        /// </summary>  
        /// <param name="id">编号</param>  
        /// <param name="item">新的学生信息</param>  
        /// <returns>更新成功返回学生信息, 否则返回null</returns>  
        [HttpPut]
        public StudentInfo UpdateStudent(int id, StudentInfo item)
        {
            try
            {
                using (DataClassesDataContext dcdc = new DataClassesDataContext())
                {
                    StudentInfo newItem = dcdc.StudentInfos
                        .FirstOrDefault(u => u.stuId == id);
                    newItem.stuName = item.stuName;
                    newItem.stuAddress = item.stuAddress;
                    dcdc.SubmitChanges();
                    return newItem;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>  
        /// 删除学生信息  
        /// DELETE /api/StudentValue/DeleteStudent/{id}  
        /// </summary>  
        /// <param name="id">编号</param>  
        /// <returns>删除成功返回true, 否则返回false</returns>  
        [HttpDelete]
        public bool DeleteStudent(int id)
        {
            try
            {
                using (DataClassesDataContext dcdc = new DataClassesDataContext())
                {
                    StudentInfo item = dcdc.StudentInfos
                        .FirstOrDefault(u => u.stuId.Equals(id));
                    dcdc.StudentInfos.DeleteOnSubmit(item);
                    dcdc.SubmitChanges();
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}  
3)修改WebApiConfig.cs内容如下,主要是修改API访问路径
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MvcApplication2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

4)用Firefox RESTClient测试编写的API

提示:在Body中添加json数据时请在Headers中添加Content-Type: application/json

修改WebAPI返回数据的样式如将返回样式改成JSON:
在Global.asax.cs添加方法
/// <summary>
/// 设置WebAPI返回的样式(XML或者JSON)
/// </summary>
/// <param name="config"></param>
void ConfigureApi(HttpConfiguration config)
{
// Remove the JSON formatter
//config.Formatters.Remove(config.Formatters.JsonFormatter);
// or
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
并在方法Application_Start中调用
ConfigureApi(GlobalConfiguration.Configuration);

 

MVC4发布到IIS,出现HTTP 错误 404.0 - Not Found的解决方法。
1)Web Site所对应的Application Pool的.NET Framework Version改成v4.0。
2)由于使用的是VS2012,只要在MVC根目录的web.config中添加
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
就行了

posted on 2016-03-04 16:22  罗小夕  阅读(9669)  评论(0编辑  收藏  举报

导航