Web端使用VUE调用WebApi接口实现用户登录及采用Token方式数据交互
作者:C/S框架网|www.cscode.ne  发布日期:2021-05-12 14:48:29
  Web端使用VUE调用WebApi接口实现用户登录及采用Token方式数据交互


Web端使用VUE调用WebApi接口实现用户登录及采用Token方式数据交互



CSFramework.WebApi控制器的接口实现:



C# Code:

[HttpPost]
[ActionName(
"vue_api")]
public IUserResponse vue_api(ModelRequestToken request)
{
  
//处理请求
  
return CommandHandler.ProcessRequest(this.Request, request, LogManager.Log);
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




命令处理程序(Command Handler):


C# Code:

using AliAdminTool.WebApi.Core;
using AliAdminTool.WebApi.Core.Interfaces;
using AliAdminTool.WebApi.Core.Models;
using AliAdminTool.WebApi.DataAccess;
using AliAdminTool.WebApi.Foundation;
using AliAdminTool.WebApi.Models;
using System.Collections.Generic;
using System.Net.Http;

namespace AliAdminTool.WebApi.Commands.Commands
{
  [CommandAttribute(CommandIDs.WebAppRequest,
"处理Web/App端请求")]
  
public class Cmd_TokenCommand : CmdBaseToken
  {
    
public Cmd_TokenCommand(HttpRequestMessage httpRequest, IUserRequestToken userRequest) : base(httpRequest, userRequest)
    {
      _Operations.Add(
"GetProductUsers");//获取用户
      
}
      
      
public override object ClientData { get; }
      
      
public override IUserResponse Accept(IUserRequestToken request)
      {
        
return this.SuccessResponse;
      }
      
      
public override IUserResponse Execute()
      {
        
        
if (_UserRequest.Operation == "GetProductUsers")
        {
          List
<auth_ProductUser> list = DBHelper.GetProductUsers();
          
          
string json = JsonConvertEx.ToJson(list);
          
          
return new ModelResponse { Code = 0, Data = json, Message = "操作成功." };
        }
        
        
return this.InvalidOperationResponse;
      }
    }
  }
  
  
  
//来源:C/S框架网 | www.csframework.com | QQ:23404761




命令处理程序编号:


C# Code:

public class CommandIDs
{
  
  
public const int WebAppRequest = 999888777;//处理Web/App端请求
  

}

//来源:C/S框架网 | www.csframework.com | QQ:23404761






接口参数模型:



C# Code:

/// <summary>
/// 用户请求统一接口(用户端:Web端,采用Token调用接口方式)
/// </summary>
public class ModelRequestToken : IUserRequestToken
{
  
public ModelRequestToken()
  {
    
this.Timestamp = "";
    
this.Data = "";
    
this.UserID = "";
    
this.Token = "";
    
this.Operation = "";
    
this.Action = 0;
  }
  
  
/// <summary>
  
/// 时间戳,格式:yyyyMMddHHmmssfff,最小单位:毫秒
  
/// </summary>
  
[JsonProperty("ts")]
  
public string Timestamp { get; set; }
  
  
/// <summary>
  
/// 接口编号
  
/// </summary>
  
[JsonProperty("act")]
  
public int Action { get; set; }
  
  
/// <summary>
  
/// 操作
  
/// </summary>
  
[JsonProperty("op")]
  
public string Operation { get; set; }
  
  
/// <summary>
  
/// 本次操作的数据(JSON或字符串)
  
/// </summary>
  
[JsonProperty("data")]
  
public string Data { get; set; }
  
  
/// <summary>
  
/// 令牌
  
/// </summary>
  
[JsonProperty("token")]
  
public string Token { get; set; }
  
  
/// <summary>
  
/// 当前用户
  
/// </summary>
  
[JsonProperty("userid")]
  
public string UserID { get; set; }
  
  
/// <summary>
  
/// 客户端信息(比如登录信息,令牌,)
  
/// </summary>
  
[JsonProperty("cdata")]
  
public string ClientData { get; set; }
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




前端vue调用webapi接口(html):



HTML Code:

<!DOCTYPE html>
<html>

<head>
    
<title>My first Vue app</title>
    
<script src="https://unpkg.com/vue"></script>
    
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
<script src="https://unpkg.com/vue-axios@3.2.4/dist/vue-axios.min.js"></script>
</head>

<body>
    
<div id="app">
        
<input type="button" value="模拟登录" @click="onLogin" />
        
        
<input type="button" value="获取产品的用户列表" @click="onGetProducts" />
    
</div>
    
    
<script>
    
    
var app = new Vue({
    el:
"#app",
    data: {
    base_url:
'http://localhost:19893',//接口地址
    
ApiKey: '6439D67E-E983-4770-AFA1-BB35F89DFB6D',
    UserID:
'1388888888',
    Password:
'cf79ae6addba60ad018347359bd144d2',
    Token:
'',
    Account:
''
    },
    methods: {
    
//用户登录,获取token
    
onLogin() {
    
var me = this
    axios.post(
this.base_url + '/api/gate/loginweb', {
    ApiKey:
this.ApiKey,
    UserID:
this.UserID,
    pwd:
this.Password,
    ts:
this.shijianfilter(new Date(), 'yyyyMMddHHmmssfff')
    }).then(
function (response) {
    console.log(response);
    
var data = JSON.parse(response.data.data)
    me.Account
= data.Account;
    me.Token
= data.Token;
    }).
catch(function (error) {
    console.log(error);
    });
    },
    
//调用webapi接口
    
onGetProducts() {
    
var me = this
    axios.post(
this.base_url + '/api/auth/vue_api', {
    act:
999888777,
    op:
'GetProductUsers',
    Token: me.Token,
    UserID: me.Account,
    Data:
'',
    cdata:
'',
    ts:
this.shijianfilter(new Date(), 'yyyyMMddHHmmssfff')
    }).then(
function (response) {
    console.log(response);
    }).
catch(function (error) {
    console.log(error);
    });
    },
    
    shijianfilter(value, args) {
    
var dt = new Date(value)
    
    
var y = dt.getFullYear()
    
//这里month得加1
    
var m = dt.getMonth() + 1
    
var d = dt.getDate()
    
//如果要求的时间格式只有年月日
    
if (args.toLowerCase() === "yyyy-mm-dd") {
    
return `${y}-${m}-${d}`
    
//如果时间要求精确到时分秒
    
} else {
    
var hh = dt.getHours()
    
var mm = dt.getMinutes()
    
var ss = dt.getSeconds();
    
return `${y}${m}${d}${hh}${mm}${ss}`
    }
    }
    },
    });
    
</script>
</body>

</html>

//来源:C/S框架网 | www.csframework.com | QQ:23404761




C# Winform前端测试:



C# Code:

static string BASE_URL = "http://localhost:19893/";

/// <summary>
/// 模拟手机登录
/// </summary>
/// <returns></returns>
public static ModelUser Login()
{
  
string url = BASE_URL + "api/gate/loginweb";
  
  ModelRequestLogin4Web requestToken
= new ModelRequestLogin4Web
  {
    ApiKey
= PrivateData.API_KEY,
    UserID
= "1388888888",//登录账号,手机号
    
Password = "cf79ae6addba60ad018347359bd144d2",
    Timestamp
= DateTime.Now.ToString("yyyyMMddHHmmssfff"),
    };
    
    
string requestJSON = JsonConvert.SerializeObject(requestToken);
    
    
string resultJSON = WebApiTools.Post(url, requestJSON);
    ModelResponse response1
= JsonConvert.DeserializeObject<ModelResponse>(resultJSON);
    
    
//转换为用户对象
    
ModelUser user = JsonConvert.DeserializeObject<ModelUser>(response1.Data);
    
return user;
  }
  
  
/// <summary>
  
/// 获取产品的用户列表
  
/// </summary>
  
/// <returns></returns>
  
public static string GetProductUsers()
  {
    ModelUser user
= Login();//登录
    

    
string token = user.Token;
    
    
string url = BASE_URL + "api/auth/vue_api";
    
    
//动态令牌方式传入WebApi接口的参数模型
    
ModelRequestToken M = new ModelRequestToken
    {
      Timestamp
= DateTime.Now.ToString("yyyyMMddHHmmss"),//时间戳
      
Action = 999888777,
      Operation
= "GetProductUsers",
      Token
= user.Token,//令牌
      
UserID = user.Account,//用户编号
      
Data = "",//客户端提交的资料,JSON格式,如查询条件,主键等资料。
      
ClientData = "",//客户端提交的资料,JSON格式,如客户端IE版本,APP资料等。
      
};
      
      
string json = JsonConvert.SerializeObject(M, JsonSettings.Current);
      
string result = WebApiTools.Post(url, json);
      
return result;
      
    }
    
    
//来源:C/S框架网 | www.csframework.com | QQ:23404761





C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务

上一篇 下一篇