CS和BS融合开发-NanUI前后端交换数据

安装包NetDimension.NanUI.DataServiceResource
在这里插入图片描述

在代码中注册数据接口包
app.UseDataServiceResource(“http”, “api.app.local”);

详细代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetDimension.NanUI;
using NetDimension.NanUI.DataServiceResource;
using NetDimension.NanUI.LocalFileResource;

namespace WindowsFormsApp1
{
    static class Program
    {
        static void Main()
        {
            // ...
            WinFormium.CreateRuntimeBuilder(env => {

                env.CustomCefSettings(settings =>
                {
                    // 在此处设置 CEF 的相关参数
                });

                env.CustomCefCommandLineArguments(commandLine =>
                {
                    // 在此处指定 CEF 命令行参数
                });

            }, app =>
            {
                // 指定启动窗体
                app.UseMainWindow(context => new MainWindow());

                //加载本地资源
                app.UseLocalFileResource("http", "static.app.local", @"D:\myGtreeCode\demo1\WindowsFormsApp1\wwwroot");

                // ...
                app.UseDataServiceResource("http", "api.app.local");
            })
            .Build()
            .Run();
        }
    }
}

新建一个HelloService.cs类文件
代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetDimension.NanUI.DataServiceResource;
using NetDimension.NanUI.ResourceHandler;


namespace WindowsFormsApp1
{
    public class HelloService : DataService
    {
        //在不指定路由特性的情况下,数据服务适配器根据数据服务的名称来生成路由。例如上面的示例将自动生成路由Hello/Hi。
        //另外,如果数据处理程序不指定 Http 方法时,任何提交的请求不论 HttpMethod 是什么方法都将命中路由。
        public ResourceResponse Hi(ResourceRequest request)
        {
            return Text("Hello NanUI!");
        }
    }
}

这样在前端就可以调用http://api.app.local/hello/hi 获取数据
前端页面

<html>

<head>

</head>

<body>
    <span>zhupengfei</span>

    <a href="http://api.app.local/hello/hi">测试一</a>

</body>

</html>

效果图
在这里插入图片描述

接下来模拟一个用户登录的过程,实现从前端获取数据,传入后端,然后后端返回数据到前端的例子。
新建一个PassportService.cs的类文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetDimension.NanUI.DataServiceResource;
using NetDimension.NanUI.ResourceHandler;


namespace WindowsFormsApp1
{
    [DataRoute("/account")]
    public class PassportService : DataService
    {
        // 用户登录模型
        public class UserInfo
        {
            public string Passport { get; set; }
            public string Password { get; set; }
        }

        // 获取当前时间戳
        private string GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        [RoutePost("user/login")]
        public ResourceResponse Login(ResourceRequest request)
        {
            // 反序列化 JSON 数据
            var result = request.DeserializeObjectFromJson<UserInfo>();

            // 模拟延迟操作
            //Task.Delay(2000).GetAwaiter().GetResult();

            // 返回登录成功
            return Json(new { success = true, timestamp = GetTimeStamp(), result });
        }
    }
}

前端的html代码,调整如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>zhupengfei nanui</title>
</head>

<body>
    <span>zhupengfei</span>

    <a href="javascript:void(0)" onclick="test1();return false;">测试一</a>

    <a href="javascript:void(0)" onclick="test2();return false;">测试二</a>
    <script>
        function test1() {
            console.log("get http://api.app.local/hello/hi");
            var xhr = new XMLHttpRequest();//第一步:新建对象
            xhr.open('GET', 'http://api.app.local/hello/hi', true);//第二步:打开连接  将请求参数写在url中 
            xhr.send();//第三步:发送请求  将请求参数写在URL中
            /**
             * 获取数据后的处理程序
             */
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var res = xhr.responseText;//获取到json字符串,解析
                    console.log(res);
                }
            };
        }

        function test2() {
            console.log("get http://api.app.local/account/user/login");
            var xhr = new XMLHttpRequest();//第一步:新建对象
            xhr.open('POST', 'http://api.app.local/account/user/login', true); // 建立连接
            xhr.setRequestHeader("Content-type", "application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
            var obj = { Passport: 'zhansgan', Password: "111111" };
            xhr.send(JSON.stringify(obj));//发送请求 将json写入send中
            /**
             * 获取数据后的处理程序
             */
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 代码逻辑
                    var res = xhr.responseText;//获取到json字符串,解析
                    console.log(res);
                }
            };
        }
    </script>
</body>

</html>

运行效果如下

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鹏展翅888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值