WebAPI 封装返回值


     /// <summary>
        /// 获取用户信息数据信息
        /// </summary>
        /// <param name="token">登录Token</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage getRoleList(String token, Boolean emptyFlag = false)
        {
            // 返回数据
            List<RoleDomain> lsDomain = null;
            try
            {
                RoleFilter filter = new RoleFilter();
                filter.SortField = " RoleName";
                lsDomain = RoleBiz.GetDomainByExactFilter(filter) as List<RoleDomain>;
                if (emptyFlag)
                {
                    lsDomain.Insert(0, new RoleDomain());
                }
            }
            catch (Exception ex)
            {
                AppLog.Error(ex);
                return JsonResultModel(Result_Error, ex.Message, lsDomain);
            }

            return JsonResultModel(Result_Success_Code, Result_Success_MSG, lsDomain);
        }

  BaseController.cs

public HttpResponseMessage JsonResultModel(Int32 resultCode, string resultMessage, object data = null)
        {
            HttpResponseMessage result = new HttpResponseMessage();
            var dataResult = new
            {
                code = resultCode,
                msg = resultMessage,
                data = data
            };
            result.Content = new StringContent(JsonConvert.SerializeObject(dataResult), Encoding.GetEncoding("UTF-8"), "application/json");
            return result;
        }

  

权限注册:

  <appSettings>
    <add key="cors_allowOrigins" value="*" />
    <add key="cors_allowHeaders" value="*" />
    <add key="cors_allowMethods" value="*" />
  </appSettings>
      //跨域配置
            var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"];
            var allowHeaders = ConfigurationManager.AppSettings["cors_allowHeaders"];
            var allowMethods = ConfigurationManager.AppSettings["cors_allowMethods"];
            var globalCors = new EnableCorsAttribute(allowOrigins, allowHeaders, allowMethods)
            {
                SupportsCredentials = true
            };
            config.EnableCors(globalCors);
            //config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Filters.Add(new WebApiAuthAttribute());

WebApiAuthAttribute.cs

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class WebApiAuthAttribute: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            HttpContext Context = HttpContext.Current;
            if ("/api/System/login".Equals(Context.Request.Path))
            {
                return;
            }
            if (Context.Request.Path.Contains("/Common/"))
            {
                return;
            }
            // 获取Token
            String token = Context.Request.QueryString["token"];
            // 获取用户
            UserDomain user = UserBiz.GetFirstDomainByExactFilter(new UserFilter() { Token = token });
            if (user == null || String.IsNullOrEmpty(user.Id))
            {
                HttpResponseMessage result = new HttpResponseMessage();
                var dataResult = new
                {
                    code = 50012,
                    msg = "系统已注销"
                };
                result.Content = new StringContent(JsonConvert.SerializeObject(dataResult), Encoding.GetEncoding("UTF-8"), "application/json");
                actionContext.Response = result;
                return;
            }
        }
    }
原文地址:https://www.cnblogs.com/byron-123/p/14203696.html