简单记录在Visual Studio 2013中创建ASP.NET Web API 2

  在很多跨平台的应用中就需要Web API ,比如android与数据库的交互。

Create a Web API Project                                                                                                      

选择新建项目下的模板下的Visual C#节点下的Web节点,在模板列表下选择ASP.NET Web 应用程序,并命名为ChatApp就可以了。

image

新建ASP.NET项目下选择Web API 点击确定就可以了。

image

Adding a Model                                                                                                                       

在解决方案下新建一个Model

//新建Model User
namespace APP_Chat.Models
{
    public class User
    {
        public string UID { get; set; }
        public string LoginName { get; set; }
        public string Name { get; set; }
        public string Pwd { get; set; } 
        public DateTime CreateTime { get; set; }

    }
}
//新建Model ResponseLoginState
namespace APP_Chat.Models
{
    public class ResponseLoginState
    {
        public User user { get; set; }
        public int state { get; set; }
        public string msg { get; set; }
    }
}
// 新建Model RequestLogin
namespace APP_Chat.Models
{
    public class RequestLogin
    {
        public string LoginName { get; set; }
        public string Pwd { get; set; }
    }
}

Adding a Controller                                                                                                                 

在解决方案下新建一个控制器

 

image

选择一个空的模板即可

image

下面就添加控制器的名称(Controller命名是有规范的,不能更改后面的Controller部分也不能在后门添加字符,不然都会导致最后无法访问到这个Controller像这个Controller就是通过/api/ChatApp/访问的,当然默认是Get的请求方式)

image

namespace APP_Chat.Controllers
{
    public class ChatAppController : ApiController
    {

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="user">用户的登录名 - LoginName,密码 - Pwd</param>
        /// <returns>登录成功则返回用户的信息,和state=1</returns>   [HttpPost] http 请求方式 
        [HttpPost] 
        public ResponseLoginState Login(RequestLogin user)
        {
            if (string.IsNullOrWhiteSpace(user.LoginName))
                return new ResponseLoginState() { state = 0, msg = "参数错误,LoginName未传出!" };
            if (string.IsNullOrWhiteSpace(user.Pwd))
                return new ResponseLoginState() { state = 0, msg = "参数错误,Name未传出!" };
            
            #region
            using (var conn = new System.Data.OracleClient.OracleConnection(OracleHelper.ConnString))
            {
                conn.Open();
                var command = conn.CreateCommand();
                command.Parameters.Clear();
                command.Parameters.Add(new OracleParameter(":loginName", user.LoginName));
                command.Parameters.Add(new OracleParameter(":pwd", user.Pwd));
                command.CommandText = "select * from APP_ChatUser where loginname=:loginName and pwd=:pwd";
                var reader = command.ExecuteReader();
                User loginuser = new User();
                try
                {
                    reader.Read();
                    loginuser.UID = reader["USERID"].ToString();
                    loginuser.LoginName = reader["LOGINNAME"].ToString();
                    loginuser.Name = reader["NAME"].ToString();
                    loginuser.Pwd = reader["PWD"].ToString();
                    loginuser.CreateTime = Convert.ToDateTime(reader["CreateTime"]);
                    return new ResponseLoginState() { state = 1, msg = "success", user = loginuser };
                }
                catch (Exception ex)
                {

                    return new ResponseLoginState() { state = 0, msg = ex.Message, user = null };
                }
            }
            #endregion
        }
   }
}
 
通过访问api/ChatApp/Login就可以访问WebApi了
JavaScript来检测WebApi                                                                   
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script>
        var user;
        
        function login() {
            $.ajax({
                url: '/api/ChatApp/Login',
                type: 'POST',
                dataType:'JSON',
                data: { LoginName: 'zhangsan', Pwd: '123' },
                success: function (data) {
                    if (typeof (data) != 'object')
                        data = JSON.parse(data);
                    user = data.Data.User;
                    alert(JSON.stringify(data));                   
                }
            });

        }

    </script>
</head>
<body>
    <input type="button" value="登录" onclick="login()" />
</body>
</html>
如果有不清楚,可以参照下面的这个网址学习http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
posted @ 2015-08-20 19:44  戴杭林  阅读(994)  评论(0编辑  收藏  举报