asp.net前端调用后端api接口

全局:

两个工程中定义用于数据交换的类

成功:

public class Success

    {

        /// <summary>

        /// 成功返回对象<br/>

        /// exp:<br/>

        /// <div style="color:red">登录成功</div>

        /// </summary>

        /// <param name="message">提示信息</param>

        /// <param name="result">数据</param>

        public Success(string message, object result)

        {

            this.code = 200;

            this.message = message;

            this.result = result;

        }

        public int code { get; set; }

        public string message { get; set; }

        public object result { get; set; }
    }

失败:

public class Error

    {

        /// <summary>

        /// 错误返回对象<br/>

        /// exp:<br/>

        /// <font style='color:red'>登录错误</font><br/>

        /// 数据库连接失败<br/>

        /// </summary>

        /// <param name="message">提示信息</param>

        public Error(string message)

        {

            this.code = -1;

            this.message = message;

            this.result = null;

        }

        public int code { get; set; }

        public string message { get; set; }

        public object result { get; set; }



    }

Api方面:

返回值为成功或者失败的类 值在类中

/// <summary>

/// 查询所有

/// </summary>

/// <returns></returns>

[HttpGet]

public object QueryAllSysuser()

{

    using (fashionshoppingDBEntities db = new fashionshoppingDBEntities())

    {

        //toList代表关闭查询(关闭长连接)

        return new Success("查询成功", db.Sysuser.ToList());

    }

}



/// <summary>

/// 根据名称查询用户

/// </summary>

/// <param name="username"></param>

/// <returns></returns>

[HttpPost]

public object QuerySysuser(string username)

{

    using (fashionshoppingDBEntities db = new fashionshoppingDBEntities())

    {

        List<Sysuser> u = null;

        if (!string.IsNullOrEmpty(username))

        {

            u = db.Sysuser.Where(o => o.username.Contains(username)).ToList();

        }

        if (u == null)

        {

            return new Error("没有此用户");

        }



        return new Success("查询成功", u);

    }

}

/// <summary>

/// 添加用户

/// </summary>

/// <param name="username">名称</param>

/// <param name="pwd">密码</param>

/// <param name="role">管理员状态</param>

/// <returns></returns>

[HttpPost]

public object SaveSysuser(string username,string pwd,string role)

{

    if (

        string.IsNullOrEmpty(username) || string.IsNullOrEmpty(pwd) ||

        string.IsNullOrEmpty(role)

        )

    {

        return new Error("参数不允许为空");

    }



    Sysuser u = new Sysuser();

    u.username = username;

    u.pwd = pwd;

    u.role = int.Parse(role);



    using (fashionshoppingDBEntities db = new fashionshoppingDBEntities())

    {

        db.Sysuser.Add(u);

        int rows = db.SaveChanges();

        if (rows > 0)

        {

            return new Success("添加成功", u.id);

        }

        return new Error("添加失败");

    }

}



/// <summary>

/// 修改用户

/// </summary>

/// <param name="id">修改的用户id</param>

/// <param name="username">修改后的name</param>

/// <param name="pwd">修改后的密码</param>

/// <param name="role">修改后的状态</param>

/// <returns></returns>

[HttpPost]

public object UpdateSysuser(int id, string username, string pwd, string role)

{

    using (fashionshoppingDBEntities db = new fashionshoppingDBEntities())

    {

        Sysuser user = db.Sysuser.Where(o => o.id.Equals(id)).SingleOrDefault();

        user.username = username;

        user.pwd = pwd;

        user.role = int.Parse(role);



        int rows = db.SaveChanges();

        if (rows > 0)

        {

            return new Success("更新成功", id);

        }

        return new Error("更新失败");

    }

}

/// <summary>

/// 删除用户

/// </summary>

/// <param name="id"> 删除用户id</param>

/// <returns></returns>

[HttpGet]

public object DeleteById(string id)

{

    if (string.IsNullOrEmpty(id))

    {

        return new Error("参数不允许为空");

    }

    using (fashionshoppingDBEntities db = new fashionshoppingDBEntities())

    {

        int Id = int.Parse(id);

        Sysuser u = db.Sysuser.Where(o => o.id.Equals(Id)).SingleOrDefault();

        if (u == null)

        {

            return new Error("没有此用户");

        }

        //删除操作

        db.Sysuser.Remove(u);

        //写入数据库

        int rows = db.SaveChanges();

        if (rows > 0)

        {

            return new Success("删除成功", rows);

        }

        return new Error("删除失败");

    }

}

前端方面:

控制器:

封装的方法:

/// <summary>

/// get请求方法

/// </summary>

/// <param name="url">请求地址</param>

/// <returns></returns>

public Success RequestGet(string url)

{

    //声明http访问

    HttpClient http = new HttpClient();

    //进行异步请求

    Task<string> task = http.GetStringAsync(url);

    //获取返回数据

    string result = task.Result;

    return JsonConvert.DeserializeObject<Success>(task.Result);

}

/// <summary>

/// post请求方式

/// </summary>

/// <param name="url">请求地址?数据</param>

/// <returns></returns>

public Success RequestPost(string url)

{

    //客户端请求

    HttpClient http = new HttpClient();

    var str = "";//请求数据。这里为空

    HttpContent content = new StringContent(str);

    //请求地址

    Task<HttpResponseMessage> postTask = http.PostAsync(url, content);

    HttpResponseMessage result = postTask.Result;//拿到网络请求结果

    result.EnsureSuccessStatusCode();//抛出异常

    Task<string> task = result.Content.ReadAsStringAsync();//异步读取数据

    //发送值前台

    return JsonConvert.DeserializeObject<Success>(task.Result);

}

Action方法:

//页面展示全部

public ActionResult Index()

{

    //访问路径

    string url = "http://localhost:16018/api/Sysuser/QueryAllSysuser";

    Success success = RequestGet(url);

    //请求成功

    if (success.code == 200)

    {

        ViewBag.message = success.message;

        ViewBag.lists = success.result;

    }

    return View();

}

页面代码:

<table border="1" cellspacing="0" cellpadding="0">

    <tr>

        <th>姓名</th>

        <th>密码</th>

        <th>角色</th>

        <th>操作</th>

    </tr>

    @foreach (var item in ViewBag.lists)

    {

        <tr>

            <td>@item.username</td>

            <td>@item.pwd</td>

            <td>

                @if (item.role == 1)

                {

                    @:系统管理员

                }

                else

                {

                    @:普通管理员

                }

            </td>

            <td>

                <a href="/Sysuser/DeleteById?id=@item.id">删除</a>

                <a href="/Sysuser/Update?id=@item.id">更新</a>

            </td>

        </tr>

    }

</table>

请求链接:

查询所有:http://localhost:16018/api/Sysuser/QueryAllSysuser

按name查询:http://localhost:16018/api/Sysuser/QuerySysuser?username={0}

按id查询:"http://localhost:16018/api/Sysuser/QuertById?id=" + id

新增用户:"http://localhost:16018/api/Sysuser/SaveSysuser?username={0}&pwd={1}&role={2}", username, pwd, role

修改用户:"http://localhost:16018/api/Sysuser/UpdateSysuser?id={0}&username={1}&pwd={2}&role={3}", id, username, pwd, role

删除用户:http://localhost:16018/api/Sysuser/DeleteById?id=" + id

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP API 接口接收与返回 是一个轻型的、安全的、跨网际的、跨语言的、跨平台的、跨环境的、跨域的、支持复杂对象传输的、支持引用参数传递的、支持内容输出重定向的、支持分级错误处理的、支持会话的、面向服务的高性能远程过程调用协议。 该版本直接解压后就可以使用,其中 属于公共文件。不论是客户端还是服务器端都需要这些文件。 是客户端文件,如果你只需要使用客户端,那么只要有上面那些公共文件和这个文件就可以使用了,使用时,直接在你的程序中包含 phprpc_client.php 就可以,公共文件不需要单独包含。 这三个文件是服务器端需要的文件。 其中 dhparams 目录中包含的是加密传输时用来生成密钥的参数 dhparams.php 是用来读取 dhparams 目录中文件的类。 phprpc_server.php 是服务器端,如果你要使用 PHP 来发布 PHPRPC 服务,只需要包含这个文件就可以了。公共文件和 dhparams.php 都不需要单独包含。 PHP 4.3+、PHP 5、PHP 6 客户端要求开启 socket 扩展。 服务器端需要有 IIS、Apache、lighttpd 等可以运行 PHP 程序的 Web 服务器。 如果服务器端需要加密传输的能力,必须要保证 session 配置正确。 <?php include('php/phprpc_server.php'); //加载文件 function hello($name) { return'Hello ' . $name; } $server = new PHPRPC_Server(); //创建服务端 $server->add(array('hello', 'md5', 'sha1')); //数组形式一次注册多个函数 $server->add('trim'); //单一注册 $server->start(); //开启服务 ?> <?php include ("php/phprpc_client.php"); //加载文件 $client = new PHPRPC_Client('http://127.0.0.1/server.php'); //创建客户端 并连接服务端文件 echo$client->Hello("word"); //调用方法 返回 hello word ?> -------------------------------------------------- --------------------------------------------------- ------------------------------ 服务端其他说明: <?php include('php/phprpc_server.php'); //加载文件 function hello($name) { return'Hello ' . $name; } class Example1 { staticfunction foo() { return'foo'; } function bar() { return'bar'; } } $server = new PHPRPC_Server(); //创建服务端 $server->add('foo', 'Example1'); //静态方法直接调用 $server->add('bar', new Example1()); //非静态方法 需要实例化 //注册别名调用 $server->add('hello', NULL, 'hi'); //第三参数是函数的别名 客户端通过别名来调用函数 $server->add('foo', 'Example1', 'ex1_foo'); $server->add('bar', new Example1(), 'ex1_bar'); $server->setCharset('UTF-8'); //设置编码 $server->setDebugMode(true); //打印错误 $server->setEnableGZIP(true); //启动压缩输出虽然可以让传输的数据量减少,但是它会占用更多的内存和 CPU,因此它默认是关闭的。 $server->start(); //开启服务 ?> -------------------------------------------------- --------------------------------------------------- ---------------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值