Blame view

Hh.Mes.Api/Controllers/BaseController.cs 1.79 KB
赖素文 authored
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hh.Mes.Common.Json;
using Hh.Mes.Common.Redis;
using Hh.Mes.POJO.Entity;
using Hh.Mes.Pojo.System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Hh.Mes.Api.Controllers
{
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 上下文
        /// </summary>
        public HttpContext context;

        /// <summary>
        /// 获取用户 
        /// 注意配置文件(appsettings)设置【RedisDb】要和中控系统【RedisDb】保持一致,否则取不到用户信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public UserAuthSession GetUser(HttpContext httpContext)
        {
            var token = GetToken(httpContext);
            return string.IsNullOrEmpty(token) ? null : new RedisBase().GetT<UserAuthSession>(token);
        }

        /// <summary>
        /// 获取 tokens
        /// </summary>
        public string GetToken(HttpContext httpContext)
        {
            var token = httpContext.Request.Query[Program.tokens];
            if (string.IsNullOrEmpty(token)) token = httpContext.Request.Cookies[Program.tokens];
            if (string.IsNullOrEmpty(token)) token = httpContext.Request.Headers[Program.tokens];
            return token;
        }

        public string Serialize(object result)
        {
            return JsonHelper.Instance.Serialize(result);
        }

        /// <summary> 
        /// 获取客户端ip 注意先依赖注入context
        /// </summary>
        /// <returns></returns>
        public string GetIp()
        {
            string ip = context.Connection.RemoteIpAddress.ToString();
            return ip;
        }

    }
}