且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

抛开MVC4使用Web API

更新时间:2022-09-16 19:20:48

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

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

抛开MVC4使用Web API

继续添加 System.Net.Http

抛开MVC4使用Web API

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

抛开MVC4使用Web API

添加路由映射

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

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;
    }
}

运行上一篇的测试程序吧




本文转自齐师傅博客园博客,原文链接:http://www.cnblogs.com/youring2/archive/2013/03/08/2949602.html,如需转载请自行联系原作者