程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 搭建一個Web API項目

搭建一個Web API項目

編輯:關於.NET

一、創建一個能跑的起來的Web API項目

1、建一個空的 ASP.NET Web應用

 

2、用NuGet引入Web API

這時我的packages

<?xml version="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.XmlConfigurator.Configure(
              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);
        }

 

附:源碼下載

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved