2013-03-08 11:28阅读: 12166评论: 4推荐: 5

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

运行上一篇的测试程序吧

本文作者:拓荒者IT

本文链接:https://www.cnblogs.com/youring2/archive/2013/03/08/2949602.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

 

📌做了个微信公众号【拓荒者IT】,分享各种技术干货,新内容首发到公众号,欢迎关注❤️

posted @   拓荒者IT  阅读(12166)  评论(4编辑  收藏  举报
皮肤配置 参考地址:https://www.yuque.com/awescnb/user
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起