给现有MVC 项目添加 WebAPI - 小y - 博客园

来源: 给现有MVC 项目添加 WebAPI – 小y – 博客园

1. 增加一个WebApi Controller, VS 会自动添加相关的引用,主要有System.Web.Http,System.Web.Http.WebHost,System.Net.Http

2. 在App_Start 下创建 WebApiConfig.cs 并注册路由

复制代码
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace Libaray.Web.App_Start
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
复制代码
复制代码

3. 在Global.asax, Application_Start 下添加 WebAPI 配置

复制代码
复制代码
using Libaray.Web.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Libaray.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
复制代码
复制代码

4. 在第一步添加的WebApi 中填写相应代码,

复制代码
复制代码
using Libaray.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Libaray.Web.Controllers
{
    [RoutePrefix("api/SystemUsers")]
    public class SystemUsersController : ApiController
    {
        [HttpGet, Route("GetUserList")]
        public List<UserModel> GetUserModels()
        {
            UserModelService UserBS = new UserModelService();
            return UserBS.FindList(u => u.isActive == true);
        }

        [HttpGet, Route("GetUser")]
        public UserModel GetUserModel(int id = 0)
        {
            if(id != 0)
            {
                UserModelService UserBS = new UserModelService();
                return UserBS.Find(u => u.Id == id);
            }
            else
            {
                return null;
            }
        }

        [HttpPost, Route("Login")]
        public bool Login(string loginId,string password)
        {
            UserModelService UserBS = new UserModelService();
            return UserBS.ValidateLoginInfo(loginId, password);
        }
    }
}


复制代码
复制代码

5. Run the application and call the API. Example: http://localhost:49919/api/SystemUsers/GetUserList

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏