BaseController.cs 1.79 KB
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;
        }

    }
}