WebApi开发爬坑记之·一重写ApiController

公司突然要求给写接口 ,虽然.net的webpai 和mvc大同小异 但是还是有些细节的地方有区别 

然后果断进入坑了

一步一步开始爬坑了!

为了便于对Controller的控制的,肯定先重写ApiController啊!

代码说话

    public class BaseController : ApiController
    {
        public int loginid { get; set; }

        public string loginname { get; set; }


        public BaseBll baseBll { get; set; }


        protected override void Initialize(HttpControllerContext controllerContext)
        {
            //初始化请求上下文
            base.Initialize(controllerContext);
            try
            {
                new SortedDictionary();
                string username = string.Empty;
                HttpRequestHeaders headers = controllerContext.Request.Headers;
                if (headers.Contains("e"))
                {
                    text = (headers.GetValues("e").FirstOrDefault().ToString() ?? string.Empty);
                    text = System.Web.HttpUtility.UrlDecode(username);
                }
                UserInfoEntity userInfo = new LoginBll().GetUserInfo(username);
                this.loginid = userInfo.LoginID;
                this.loginname = userInfo.LoginName;
                List tempList = userInfo.UserRole.UserAuthority;
                //不存在安全问题 后续文章有权限验证
                if (tempList.Where(c => c.AuthorityName == "权限名称").ToList().Count > 0)
                {   
                    //调用一个有权限的bll层
                    this.baseBll = new SeniorBll();
                }
                else
                { 
                    //调用一个没有权限的bll层
                    this.baseBll = new OrdinaryBll();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("Initialize", ex);
            }
        }
        /// 
        /// 设置action返回信息
        /// 
        /// 返回实体
        /// 
        protected HttpResponseMessage GetHttpResponseMessage(object result)
        {
            BaseResponseEntity responseBaseEntity = new BaseResponseEntity(0, result, string.Empty);
            return new HttpResponseMessage()
            {
                Content =
                   new StringContent(JsonConvert.SerializeObject(responseBaseEntity, dtConverter), System.Text.Encoding.UTF8,
                       "application/json")
            };
        }
        /// 
        /// 设置action返回信息
        /// 
        /// 返回实体
        /// 返回的信息参数
        /// 
        protected HttpResponseMessage GetHttpResponseMessage(object result, ref string msg)
        {
            BaseResponseEntity responseBaseEntity = new BaseResponseEntity(0, result, msg ?? string.Empty);
            return new HttpResponseMessage()
            {
                Content =
                   new StringContent(JsonConvert.SerializeObject(responseBaseEntity, dtConverter), System.Text.Encoding.UTF8,
                       "application/json")
            };
        }
    } 
  

你可能感兴趣的:(.Net,WebApi)