给现有MVC项目添加WebAPI的方法

时间:2021-04-16

  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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章