zoukankan      html  css  js  c++  java
  • 抛开MVC4使用Web API 拓荒者

    在上一篇博文WebAPI用法中说了一下Web API在MVC4中使用的样例。但有些时候我们只是想使用Web API的功能,而不需要使用整个的MVC,这个时候就该抛开MVC4来新建项目了。

    首先要新建一个asp.net空应用程序,在程序中添加引用System.Web.Http和System.Web.Http.WebHost:

    image

    继续添加 System.Net.Http

    image

    另外还需要引用Json.net,可以通过Nuget或者直接用用下载好的dll

    image

    添加路由映射

    这一步和上一篇中讲的一样,我们可以直接把上一篇的配置拿过来:

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

    新建Global.asax文件,在Application_Start中调用完成注册

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

    创建Web API Controller

    先在项目中把UserModel添加到项目中

    public class UserModel
    {
        public string UserID { get; set; }
        public string UserName { get; set; }
    }

    在项目中新建API目录,把上一篇中的UserController直接拿过来

    public class UserController : ApiController
    {
        public UserModel getAdmin()
        {
            return new UserModel() { UserID = "000", UserName = "Admin" };
        }
    
        public bool add(UserModel user)
        {
            return user != null;
        }
    }

    运行上一篇的测试程序吧

  • 相关阅读:
    前端基础开发之HTML
    内置函数(二)
    html
    内置函数(一)
    二进制安装mysql
    .net Parallel并行使用
    MVC 枚举绑定 DropDownList
    MVC扩展Url.Action方法解决复杂对象参数问题
    Index.cshtml”处的视图必须派生自 WebViewPage 或 WebViewPage<TModel>。
    设置网站URL启动
  • 原文地址:https://www.cnblogs.com/youring2/p/2949602.html
Copyright © 2011-2022 走看看