你的位置:首页 > ASP.net教程

[ASP.net教程]搭建一个Web API项目


一、创建一个能跑的起来的Web API项目

1、建一个空的 ASP.NET Web应用

 

2、用NuGet引入Web API

这时我的packages

<?"1.0" encoding="utf-8"?><packages> <package id="Microsoft.AspNet.Cors" version="5.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebApi.Cors" version="5.2.3" targetFramework="net45" /> <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" /> <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" /></packages>

 

3、App_Start下创建一个WebApiConfig.cs类,作为api启动配置类

  代码如下

using System.Web.Http;using System.Web.Http.Cors;namespace Frozen.API{  public class WebApiConfig  {    public static void Register(HttpConfiguration config)    {      //启用跨域      var cors = new EnableCorsAttribute("*", "*", "*");      config.EnableCors(cors);      // Web API routes      config.MapHttpAttributeRoutes();      config.Routes.MapHttpRoute(        name: "DefaultApi",        routeTemplate: "api/{controller}/{id}",        defaults: new { id = RouteParameter.Optional }      );    }  }}

 

4、添加“全局应用程序类” Global.asax

   Application_Start方法如下

    protected void Application_Start(object sender, EventArgs e)    {      GlobalConfiguration.Configure(WebApiConfig.Register);    }

 

5、添加一个Web API控制器类,比如”StudentController“

  初始代码如下(常用的还有个Patch方法)

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;namespace Frozen.API.Controllers{  public class StudentController : ApiController  {    // GET api/<controller>    public IEnumerable<string> Get()    {      return new string[] { "value1", "value2" };    }    // GET api/<controller>/5    public string Get(int id)    {      return "value";    }    // POST api/<controller>    public void Post([FromBody]string value)    {    }    // PUT api/<controller>/5    public void Put(int id, [FromBody]string value)    {    }    // DELETE api/<controller>/5    public void Delete(int id)    {    }  }}

 

6、绑定下测试域名

  别忘了在hosts做下指向

   

 

7、感觉可以跑起来了。启动程序,连Global都没进,直接报了500,错误提示是”由于权限不足而无法读取配置文件“

 很明显的权限问题,解决方案文件夹,右键属性,安全选项卡,添加‘Everyone’,将‘修改’权限打开,解决问题

 

8、提前在‘public string Get(int id)’处加好断点,在浏览器输入‘http://api.frozen.com/api/student/1’

  命中断点

 

二、搭建基础框架

1、按ABP,初始的架构,被我搭建成了这样

 

2、注册Autofac

从NuGet安装Autofac,关键代码如下:

    public static void SetAutofacContainer()    {      var builder = new ContainerBuilder();      builder.RegisterApiControllers(Assembly.GetExecutingAssembly());      builder.RegisterType<InMemoryCache>().As<ICache>().InstancePerLifetimeScope();      builder.RegisterAssemblyTypes(typeof(StuEducationRepo).Assembly)        .Where(t => t.Name.EndsWith("Repo"))        .AsImplementedInterfaces().InstancePerLifetimeScope();      builder.RegisterAssemblyTypes(typeof(StudentManager).Assembly)        .Where(t => t.Name.EndsWith("Manager"))        .AsImplementedInterfaces().InstancePerLifetimeScope();      builder.RegisterAssemblyTypes(typeof(StuEducationAppService).Assembly)        .Where(t => t.Name.EndsWith("AppService"))        .AsImplementedInterfaces().InstancePerLifetimeScope();      builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);      IContainer container = builder.Build();      var resolver = new AutofacWebApiDependencyResolver(container);      // Configure Web API with the dependency resolver.      GlobalConfiguration.Configuration.DependencyResolver = resolver;    }

 

3、注册AutoMapper

从NuGet安装AutoMapper,关键代码如下:

   Mapper.Initialize(x =>      {        x.AddProfile<DomainToDtoProfile>();        x.AddProfile<DtoToDomainProfile>();      });

  public class DomainToDtoProfile : Profile  {    public override string ProfileName    {      get { return "DomainToDtoMappings"; }    }    protected override void Configure()    {      Mapper.CreateMap<TB_Stu_Education, StuEducationDto>()        .ForMember(dest => dest.DegreeName, opt => opt.ResolveUsing<DegreeNameResolver>().FromMember(s => s.DegreeId))        ;    }  }

 

4、注册log4net

从NuGet安装log4net,关键代码如下,添加配置文件“\Config\log4net.config”

      log4net.Config.new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Config\\log4net.config")      );

  public class Log4NetLogger : ILogger  {    private static readonly ILog loginfo;    private static readonly ILog logerror;    private static readonly ILog logmonitor;    static Log4NetLogger()    {      //不同类型的日志 存放在 不同 的 目录中      loginfo = LogManager.GetLogger("loginfo");      logerror = LogManager.GetLogger("logerror");      logmonitor = LogManager.GetLogger("logmonitor");    }    public void Info(string message)    {      if (loginfo.IsInfoEnabled)        loginfo.Info(message);    }    public void InfoFormat(string format, params object[] args)    {      if (loginfo.IsInfoEnabled)        loginfo.InfoFormat(format, args);    }    public void Warn(string message)    {      if (loginfo.IsWarnEnabled)        loginfo.Warn(message);    }    public void Error(string message, Exception ex = null)    {      if (logerror.IsErrorEnabled)      {        if (ex != null)        {          logerror.Error(message, ex);        }        else        {          logerror.Error(message);        }      }    }    public void Monitor(string message)    {      if (logmonitor.IsInfoEnabled)        logmonitor.Info(message);    }  }

 

三、调试API接口(Fiddler)

1、GET 获取

http://api.frozen.com/api/StuEducation/1

返回:{"DegreeName":"本科","Id":1,"StuId":1,"DegreeId":2,"SchoolName":"安徽大学","MajorName":"计算机科学与技术","StartDate":"2008-09-01 00:00:00","EndDate":"2012-06-01 00:00:00","CreateTime":"2015-01-01 00:00:00","LastModifyTime":null}

代码:

    public StuEducationDto Get(int id)    {      var dto = _stuEducationAppService.GetDTOById(id);      return dto;    }

 

2、POST 新增

返回

HTTP/1.1 201 Created

代码:

    public HttpResponseMessage Post([FromBody]StuEducationDto dto)    {      int result = _stuEducationAppService.CreateByDTO(dto);      return result > 0 ? Request.CreateResponse(HttpStatusCode.Created) : Request.CreateResponse(HttpStatusCode.InternalServerError);    }

 

3、PUT 新增/修改

代码:

    public HttpResponseMessage Put(int id, [FromBody]StuEducationDto dto)    {      var result = _stuEducationAppService.CreateOrUpdateByDTO(id, dto);      return result > 0 ? Request.CreateResponse(HttpStatusCode.OK) : Request.CreateResponse(HttpStatusCode.InternalServerError);    }

 

4、Patch 局部更新

代码(使用了dynamic参数):

    public HttpResponseMessage Patch(int id, dynamic dtoUpdate)    {      var dto = _stuEducationAppService.GetDTOById(id);      if (dto == null)      {         return Request.CreateResponse(HttpStatusCode.PaymentRequired);      }      foreach (JProperty prop in dtoUpdate)      {        switch (prop.Name.ToLower())        {          case "degreeid":            dto.DegreeId = prop.Value.ToObject<int>();            break;          case "schoolname":            dto.SchoolName = prop.Value.ToObject<string>();            break;          case "majormame":            dto.SchoolName = prop.Value.ToObject<string>();            break;          case "startdate":            dto.StartDate = prop.Value.ToObject<DateTime>();            break;          case "enddate":            dto.EndDate = prop.Value.ToObject<DateTime>();            break;          default:             break;        }      }      var result = _stuEducationAppService.UpdateByDTO(id, dto);      return result > 0 ? Request.CreateResponse(HttpStatusCode.OK) : Request.CreateResponse(HttpStatusCode.NotFound);    }

 

5、Delete 删

代码:

    public HttpResponseMessage Delete(int id)    {      var result = _stuEducationAppService.DeleteById(id);      return result > 0 ? Request.CreateResponse(HttpStatusCode.OK) : Request.CreateResponse(HttpStatusCode.NotFound);    }

 

附:源码下载