net 通用接口返回类型

ResponseResult

 

    /// <summary>
    /// 返回值
    /// </summary>
    public class ResponseResult
    {
        public ResponseResult()
        {
        }

        public ResponseResult(int code)
        {
            this.Code = code;
        }

        public int Code { get; set; } = 1;

        public string Message { get; set; } = "success";
    }

    public class ResponseResult<T> 
    {
        public ResponseResult()
        {
        }

        public ResponseResult(int code ,T data)
        {
            this.Code = code;
            this.Data = data;
        }

        public int Code { get; set; } = 1;

        public string Message { get; set; } = "success";

        public T Data { get; set; }

    }


    public class PageResult<T> where T : new()
    {
        public PageResult()
        {
            Data = new T();
            Pagination = new Pagination();
        }

        public int Code { get; set; } = 0;

        public T Data { get; set; }

        public Pagination Pagination { get; set; }
    }

    public class Pagination
    {
        public Pagination()
        {
            this.TotalPage = (Total % PageSize == 0 ? (Total / PageSize) : (Total / PageSize + 1));
        }

        public int PageSize { get; set; }

        public int CurrentPage { get; set; }

        public int Total { get; set; }

        public int TotalPage { get; set; }
    }
View Code

 

通用返回驼峰规范

 

        public static string CamelCaseJson(object data)
        {
            return JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }
View Code

 

chat

private readonly InputDataExecute _inputDataExecute;
        private readonly ExportDataExecute _exportDataExecute;

        public ChatHub(InputDataExecute inputDataExecute, ExportDataExecute exportDataExecute)
        {
            _exportDataExecute = exportDataExecute;
            _inputDataExecute = inputDataExecute;
        }

        /// <summary>
        /// 发送消息给全部用户
        /// </summary>
        /// <param name="message"></param>
        /// <param name="messageType"></param>
        /// <returns></returns>
        public async Task SendMessageToAllUser(string message, string messageType = "ReceiveMessage")
        {
            await Clients.All.SendAsync(messageType, message);
        }

        /// <summary>
        /// 发送消息给单用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <param name="messageType"></param>
        /// <returns></returns>
        public async Task SendMessageToUser(string user, string message, string messageType = "ReceiveMessage")
        {
            await Clients.Group(user).SendAsync(messageType, message);
        }

        /// <summary>
        /// 发送消息给当前连接用户
        /// </summary>
        /// <param name="message"></param>
        /// <param name="messageType"></param>
        /// <returns></returns>
        public async Task SendMessageToConnection(string message, string messageType = "ReceiveMessage")
        {
            await this.Clients.Client(Context.ConnectionId).SendAsync(messageType, message);
        }

        public async Task InputData(string message)
        {
            await _inputDataExecute.Execute(JsonSerializerOptionsUtils.Deserialize<InputDataMessageRequest>(message), this, Context);
        }

        public async Task ExportData(string message)
        {
            await _exportDataExecute.Execute(JsonSerializerOptionsUtils.Deserialize<ExportDataMessageRequest>(message), this, Context);
        }

        public override Task OnConnectedAsync()
        {
            //没有登录情况下,直接关闭连接
            if (Context.User is MymoooPrincipal)
            {
                this.Groups.AddToGroupAsync(Context.ConnectionId, ((MymoooPrincipal)Context.User).User.Code);
            }
            else
            {
                this.Clients.Client(Context.ConnectionId).SendAsync("ReceiveMessage", JsonSerializerOptionsUtils.Serialize(new { ErrorMessage = "未登录情况下,不能连接!"}));
                Context.Abort();
            }
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            if (Context.User is MymoooPrincipal)
            {
                Groups.RemoveFromGroupAsync(Context.ConnectionId, ((MymoooPrincipal)Context.User).User.Code);
            }
            return base.OnDisconnectedAsync(exception);
        }
    }
View Code

 

        // 处理导出
        handleExport() {
            const { page, limit } = this.listQuery
            let filter = {
                companyName: this.form.companyName,
                salesMan: this.form.salesMan,
                startDate: this.form.quoteDate && this.form.quoteDate[0],
                endDate: this.form.quoteDate && this.form.quoteDate[1]
            }
            openLoading()
            exportQuoteDataAnalysis({ pageIndex: page, pageSize: limit, filter }).then(res => {
                const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;' })
                const a = document.createElement('a')
                a.style.display = 'none'
                // 生成文件路径
                a.href = window.URL.createObjectURL(blob)
                let _fileName = res.headers['content-disposition']
                    .split(';')[1]
                    .split('=')[1]
                    .split('.')[0]
                // 文件名中有中文 则对文件名进行转码
                a.download = decodeURIComponent(_fileName)
                // 利用a标签做下载
                document.body.appendChild(a)
                a.click()
                this.$message({
                    message: '导出成功',
                    type: 'success'
                })
                document.body.removeChild(a)
                window.URL.revokeObjectURL(a.href)
                closeLoading()
            })
        },

        // 导出全部
        handleExportAll() {
            this.$confirm('导出全部列表所需要的时间比较长,需要耐心等待,请确认是否全部导出?', '提示', {
                confirmButtonText: '',
                cancelButtonText: '',
                type: 'warning'
            })
                .then(() => {
                    this.exportVisible = true
                    this.percentage = 0
                    var that = this
                    this.connection = new signalR.HubConnectionBuilder()
                        .withUrl('/chatHub', {
                            skipNegotiation: true,
                            transport: signalR.HttpTransportType.WebSockets
                        })
                        .configureLogging(signalR.LogLevel.Information)
                        .build()
                    this.connection.on('ExportData', function(message) {
                        // console.log(message)
                        let res = JSON.parse(message)
                        that.percentage = res.progress
                        if (res.progress === 100) {
                            let exportUrl = res.filePath && res.filePath.slice(7)
                            const a = document.createElement('a')
                            a.style.display = 'none'
                            // 生成文件路径
                            a.href = exportUrl
                            document.body.appendChild(a)
                            a.click()
                            document.body.removeChild(a)
                            that.$message.success('导出成功')
                            that.exportVisible = false
                        }
                    })
                    let filter = {
                        companyName: this.form.companyName,
                        salesMan: this.form.salesMan,
                        startDate: this.form.quoteDate && this.form.quoteDate[0],
                        endDate: this.form.quoteDate && this.form.quoteDate[1]
                    }
                    let params = {
                        type: 'quotedataanalysis',
                        filter
                    }
                    this.connection.start().then(() => {
                        this.connection.invoke('ExportData', JSON.stringify(params)).catch(function(err) {
                            return console.error(err)
                        })
                    })
                    var tryingToReconnect = false
                    this.connection.disconnected(function() {
                        //TODO: write the logic to reconnect to server.
                        if (!tryingToReconnect) {
                            // notifyclient about disconnection
                            setTimeout(function() {
                                this.connection.start()
                            }, 5000) // Restart connection after 5 seconds.
                        }
                    })
                    this.connection.reconnecting(function() {
                        tryingToReconnect = true
                        console.log('reconnecting...')
                    })
                    this.connection.reconnected(function() {
                        tryingToReconnect = false
                        console.log('Reconnected')
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消导出'
                    })
                })
        }
View Code

 

posted @ 2021-06-25 11:26  bxzjzg  阅读(148)  评论(0编辑  收藏  举报