/// <summary>
 /// 用户登陆(将已经生成的JWT身份认证信息写入到Cookie)
 /// 若要使用Cookie+JWT验证,需要在Startup中配置app.UseJWTAuthenticationWithCookie
 /// </summary>
 public static void UserSignInWithJWT(this Controller controller, JsonWebToken.JwtToken jwt, bool secureCookie = true, CookieOptions options = null)
 {
     options          = options ?? options ?? new CookieOptions();
     options.Secure   = secureCookie;
     options.HttpOnly = true;
     controller.HttpContext.Response.Cookies.Append(jwt.key, jwt.access_token, options);
 }
Exemplo n.º 2
0
        public static RequestHandler OData(
            this Microsoft.AspNetCore.Mvc.Controller ctrl,
            TableSpec tableSpec,
            IQueryPipe sqlQuery,
            ODataHandler.Metadata metadata = ODataHandler.Metadata.NONE,
            string metadataUrl             = null)
        {
            var querySpec = SqlServerRestApi.OData.UriParser.Parse(tableSpec, ctrl.Request);
            var sql       = QueryBuilder.Build(querySpec, tableSpec);

            if (!querySpec.count)
            {
                if (metadata == ODataHandler.Metadata.NONE)
                {
                    sql = sql.AsJson("value");
                }
                else
                {
                    sql = sql.AsJson();
                }
            }
            return(new ODataHandler(sql, sqlQuery, ctrl.Response, tableSpec,
                                    metadataUrl ??
                                    ((ctrl is ODataController) ? (ctrl as ODataController).MetadataUrl : null) ??
                                    ((ctrl.Request.Scheme + "://" + ctrl.Request.Host + ctrl.Request.Path.Value.Replace("/" + tableSpec.Name, ""))), metadata, countOnly: querySpec.count));
        }
Exemplo n.º 3
0
 /// <summary>
 /// success status
 /// </summary>
 /// <param name="controller">控制器</param>
 /// <returns>jsonResult</returns>
 public static Microsoft.AspNetCore.Mvc.JsonResult JsonSuccessStatus(this Microsoft.AspNetCore.Mvc.Controller controller)
 {
     return(controller.Json(new JsonResponse()
     {
         StatusCode = ResponseStatus.请求成功, Message = ResponseStatus.请求成功.ToString()
     }, defaultJSS));
 }
Exemplo n.º 4
0
 /// <summary>
 /// other stauts
 /// </summary>
 /// <param name="controller">控制器</param>
 /// <param name="actionParams">状态参数</param>
 /// <returns>jsonResult</returns>
 public static Microsoft.AspNetCore.Mvc.JsonResult JsonOtherStatus(this Microsoft.AspNetCore.Mvc.Controller controller, ResponseStatus actionParams)
 {
     return(controller.Json(new JsonResponse()
     {
         StatusCode = actionParams, Message = actionParams.ToString()
     }, defaultJSS));
 }
        //private static ILog _log = null;
        public static RequestHandler OData(
            this Microsoft.AspNetCore.Mvc.Controller ctrl,
            TableSpec tableSpec,
            ODataHandler.Metadata metadata = ODataHandler.Metadata.NONE,
            string metadataUrl             = null,
            object id = null)
        {
            return(ctrl.Request.OData(tableSpec, ctrl.Response, metadata,
                                      metadataUrl: metadataUrl ??
                                      ((ctrl is ODataController) ? (ctrl as ODataController).MetadataUrl : null) ??
                                      ((ctrl.Request.Scheme + "://" + ctrl.Request.Host + ctrl.Request.Path.Value.Replace("/" + tableSpec.Name, ""))),
                                      id: id));

            #region Extracted & refactored

            /*
             * if (_log == null)
             *  _log = StartUp.GetLogger<RequestHandler>();
             * try
             * {
             *  var querySpec = SqlServerRestApi.OData.UriParser.Parse(tableSpec, ctrl.Request);
             *  if (id != null)
             *  {
             *      querySpec.predicate = tableSpec.primaryKey + " = @Id";
             *      var p = new SqlParameter("Id", id);
             *      if (querySpec.parameters == null)
             *      {
             *          querySpec.parameters = new System.Collections.Generic.LinkedList<SqlParameter>();
             *      }
             *      querySpec.parameters.AddFirst(p);
             *  }
             *  var sql = QueryBuilder.Build(querySpec, tableSpec);
             *
             *  if (id != null)
             *  {
             *      sql = sql.AsSingleJson();
             *  }
             *  else if (!querySpec.count)
             *  {
             *      if (metadata == ODataHandler.Metadata.NONE)
             *          sql = sql.AsJson("value");
             *      else
             *          sql = sql.AsJson();
             *  }
             *
             *  return new ODataHandler(sql, sqlQuery, ctrl.Response, tableSpec,
             *      metadataUrl ??
             *      ((ctrl is ODataController) ? (ctrl as ODataController).MetadataUrl : null) ??
             *      ((ctrl.Request.Scheme + "://" + ctrl.Request.Host + ctrl.Request.Path.Value.Replace("/" + tableSpec.Name, ""))), metadata,
             *      countOnly: querySpec.count,
             *      returnSingleResult: (id != null));
             * } catch (Exception ex)
             * {
             *  return new ErrorResponseHandler(ctrl.Response, ex);
             * }
             */
            #endregion
        }
Exemplo n.º 6
0
 public static string GetCustomerId(this Microsoft.AspNetCore.Mvc.Controller controller)
 {
     Microsoft.Extensions.Primitives.StringValues customerId = Microsoft.Extensions.Primitives.StringValues.Empty;
     if (!controller.HttpContext.Request.Headers.TryGetValue("customerId", out customerId))
     {
         return(string.Empty);
     }
     return(customerId.ToString().ToLower());
 }
Exemplo n.º 7
0
        // --------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Get a component with a dummy view context in order to be rendered directly from a controller.
        /// </summary>
        /// <typeparam name="T">The type of component to create.</typeparam>
        /// <param name="controller">The controller to create the component for.</param>
        public static T GetComponent <T>(this Microsoft.AspNetCore.Mvc.Controller controller) where T : class, ITagComponent
        {
            var component = controller?.HttpContext?.GetService <T>();

            if (component.Page == null)
            {
                component.Page = new _TempViewPage(controller.ControllerContext);
            }
            return((T)component);
        }
Exemplo n.º 8
0
        public string GetUserId(Microsoft.AspNetCore.Mvc.Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = "";

            return(user.ToString());
        }
Exemplo n.º 9
0
        public static RequestHandler OData(
            this Microsoft.AspNetCore.Mvc.Controller ctrl,
            TableSpec tableSpec,
            IQueryPipe sqlQuery,
            ODataHandler.Metadata metadata = ODataHandler.Metadata.NONE,
            string metadataUrl             = null,
            object id = null)
        {
            if (_log == null)
            {
                _log = StartUp.GetLogger <RequestHandler>();
            }
            try
            {
                var querySpec = SqlServerRestApi.OData.UriParser.Parse(tableSpec, ctrl.Request);
                if (id != null)
                {
                    querySpec.predicate = tableSpec.primaryKey + " = @Id";
                    var p = new SqlParameter("Id", id);
                    if (querySpec.parameters == null)
                    {
                        querySpec.parameters = new System.Collections.Generic.LinkedList <SqlParameter>();
                    }
                    querySpec.parameters.AddFirst(p);
                }
                var sql = QueryBuilder.Build(querySpec, tableSpec);

                if (id != null)
                {
                    sql = sql.AsSingleJson();
                }
                else if (!querySpec.count)
                {
                    if (metadata == ODataHandler.Metadata.NONE)
                    {
                        sql = sql.AsJson("value");
                    }
                    else
                    {
                        sql = sql.AsJson();
                    }
                }

                return(new ODataHandler(sql, sqlQuery, ctrl.Response, tableSpec,
                                        metadataUrl ??
                                        ((ctrl is ODataController) ? (ctrl as ODataController).MetadataUrl : null) ??
                                        ((ctrl.Request.Scheme + "://" + ctrl.Request.Host + ctrl.Request.Path.Value.Replace("/" + tableSpec.Name, ""))), metadata,
                                        countOnly: querySpec.count,
                                        returnSingleResult: (id != null)));
            } catch (Exception ex)
            {
                return(new ErrorResponseHandler(ctrl.Response, ex));
            }
        }
        public static RequestHandler Table(
            this Microsoft.AspNetCore.Mvc.Controller ctrl,
            TableSpec tableSpec)
        {
            var querySpec = MsSql.TableApi.UriParser.Parse(tableSpec, ctrl.Request);
            var sql       = QueryBuilder.Build(querySpec, tableSpec);

            if (!querySpec.count)
            {
                sql = sql.AsJson();
            }
            return(new JQueryDataTablesHandler(sql, ctrl.Request.Query["draw"].ToString(), Convert.ToInt32(ctrl.Request.Query["start"]), Convert.ToInt32(ctrl.Request.Query["length"]), ctrl.Response));
        }
Exemplo n.º 11
0
        /// <summary>
        /// 获取第一条验证失败的信息
        /// </summary>
        public static ModelError FirstError(this Microsoft.AspNetCore.Mvc.Controller controller)
        {
            var error = new ModelError(string.Empty);

            foreach (var item in controller.ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    error = item.Errors.First();
                }
            }
            return(error);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 注销登陆(删除Cookie中的JWT身份凭证)
        /// tokenKey 为 null 时将会尝试从配置文件 JWT:Name 中获取
        /// </summary>
        public static void UserSignOutWithJWT(this Controller controller, string tokenKey = null, bool secureCookie = true, CookieOptions options = null)
        {
            options          = options ?? new CookieOptions();
            options.Secure   = secureCookie;
            options.HttpOnly = true;

            if (tokenKey.IsNullOrEmpty())
            {
                tokenKey = controller.GetRequiredService <IConfiguration>().GetValue <string>(JsonWebToken.TokenNamePath);
                if (tokenKey.IsNullOrEmpty())
                {
                    tokenKey = JsonWebToken.TokenNameDefault;
                }
            }
            controller.HttpContext.Response.Cookies.Delete(tokenKey, options);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 用户登陆
        /// 需要在 Startup 中配置Session及Cookie基本信息
        /// services.AddSessionAndCookie();
        /// app.UseAuthentication();
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="userName">用户名</param>
        /// <param name="userId">用户ID</param>
        /// <param name="roles">用户角色</param>
        /// <param name="claims">其他标识</param>
        public static void UserSignIn(this Controller controller, string userName, long userId, string[] roles = null, params Claim[] claims)
        {
            var newClaims = claims.ToList();

            newClaims.Add(new Claim(ClaimTypes.Name, userName));
            foreach (var role in roles)
            {
                newClaims.Add(new Claim(ClaimTypes.Role, role));
            }
            newClaims.Add(new Claim(ClaimTypes.NameIdentifier, userId.ToString()));

            controller.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                               new ClaimsPrincipal(
                                                   new ClaimsPrincipal(
                                                       new ClaimsIdentity(newClaims, CookieAuthenticationDefaults.AuthenticationScheme)
                                                       )
                                                   )
                                               ).Wait();
        }
Exemplo n.º 14
0
        /// <summary>
        /// success
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="jsonObject">要序列化的JsonResponse</param>
        /// <param name="limitParams">要显示的参数数组</param>
        /// <returns>jsonResult</returns>
        public static Microsoft.AspNetCore.Mvc.JsonResult JsonSuccessWithLimit(this Microsoft.AspNetCore.Mvc.Controller controller, JsonResponse jsonObject, string[] limitParams = null)
        {
            JsonSerializerSettings settings;

            if (limitParams == null)
            {
                settings = defaultJSS;
            }
            else
            {
                string[] parmas = new string[limitParams.Length + 2];
                parmas[0] = "StatusCode";
                parmas[1] = "Message";
                limitParams.CopyTo(parmas, 2);
                settings = new JsonSerializerSettings()
                {
                    ContractResolver = new LimitPropsContractResolver(parmas)
                };
            }
            jsonObject.StatusCode = ResponseStatus.请求成功;
            jsonObject.Message    = ResponseStatus.请求成功.ToString();
            return(controller.Json(jsonObject, settings));
        }
Exemplo n.º 15
0
 /// <summary>
 /// 自定义模型验证器
 /// </summary>
 public static ModelValidate ModelValidate(this Microsoft.AspNetCore.Mvc.Controller controller, params object[] models)
 {
     return(new ModelValidate(models));
 }
Exemplo n.º 16
0
 /// <summary>
 /// 返回json
 /// </summary>
 /// <param name="controller"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 public static Microsoft.AspNetCore.Mvc.JsonResult ToJsonResult(this Microsoft.AspNetCore.Mvc.Controller controller, object result)
 {
     return(controller.Json(result, new Newtonsoft.Json.JsonSerializerSettings()));
 }
Exemplo n.º 17
0
 public static void info(this Microsoft.AspNetCore.Mvc.Controller controller, string message)
 {
     controller.TempData["MsgInfo"] = message;
 }
Exemplo n.º 18
0
 public static void success(this Microsoft.AspNetCore.Mvc.Controller controller, string message)
 {
     controller.TempData["MsgSuccess"] = message;
 }
Exemplo n.º 19
0
 public static void danger(this Microsoft.AspNetCore.Mvc.Controller controller, string message)
 {
     controller.TempData["MsgDanger"] = message;
 }
Exemplo n.º 20
0
 public static void warning(this Microsoft.AspNetCore.Mvc.Controller controller, string message)
 {
     controller.TempData["MsgWarning"] = message;
 }
Exemplo n.º 21
0
 /// <summary>
 /// 获取已注入的服务实例
 /// </summary>
 public static T GetRequiredService <T>(this Controller controller)
 => controller.HttpContext.RequestServices.GetRequiredService <T>();
        /// <summary>
        /// jsonResponse convert to jsonResult
        /// </summary>
        /// <param name="obj">object</param>
        /// <param name="controller">current controller</param>
        /// <returns></returns>
        public static Microsoft.AspNetCore.Mvc.JsonResult ToJsonSuccess(this object obj, Microsoft.AspNetCore.Mvc.Controller controller, JsonSerializerSettings serializerSettings = null)
        {
            var resp = new JsonResponse1 <object> {
                JsonData = obj
            };

            return(controller.JsonSuccess(resp, serializerSettings));
        }
Exemplo n.º 23
0
 /// <summary>
 /// success
 /// </summary>
 /// <param name="controller">控制器</param>
 /// <param name="jsonObject">要序列化的JsonResponse</param>
 /// <param name="serializerSettings">json设置</param>
 /// <returns>jsonResult</returns>
 public static Microsoft.AspNetCore.Mvc.JsonResult JsonSuccess(this Microsoft.AspNetCore.Mvc.Controller controller, JsonResponse jsonObject, JsonSerializerSettings serializerSettings = null)
 {
     jsonObject.StatusCode = ResponseStatus.请求成功;
     jsonObject.Message    = ResponseStatus.请求成功.ToString();
     return(controller.Json(jsonObject, serializerSettings ?? defaultJSS));
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="controller"></param>
        /// <param name="limitParams"></param>
        /// <returns></returns>
        public static Microsoft.AspNetCore.Mvc.JsonResult ToJsonSuccessWithLimit(this object obj, Microsoft.AspNetCore.Mvc.Controller controller, string[] limitParams = null)
        {
            var resp = new JsonResponse1 <object> {
                JsonData = obj
            };

            return(controller.JsonSuccessWithLimit(resp, limitParams));
        }
Exemplo n.º 25
0
 /// <summary>
 /// Convert To Json Result
 /// </summary>
 /// <param name="controller">控制器</param>
 /// <returns>JsonResult</returns>
 public Microsoft.AspNetCore.Mvc.JsonResult ToJsonResult(Microsoft.AspNetCore.Mvc.Controller controller)
 {
     return(controller.JsonSuccess(this));
 }
Exemplo n.º 26
0
 public static RequestHandler JQueryDataTables(this Microsoft.AspNetCore.Mvc.Controller ctrl,
                                               TableSpec tableSpec,
                                               IQueryPipe sqlQuery)
 {
     return(Table(ctrl, tableSpec, sqlQuery));
 }
Exemplo n.º 27
0
        /// <summary>
        /// Gets the current Audit Scope.
        /// </summary>
        /// <param name="controller">The MVC controller.</param>
        /// <returns>The current Audit Scope or NULL.</returns>
#if NETSTANDARD1_6
        public static AuditScope GetCurrentAuditScope(this Microsoft.AspNetCore.Mvc.Controller controller)
        {
            return(AuditAttribute.GetCurrentScope(controller.HttpContext));
        }
 public static CancellationToken _GetRequestCancellationToken(this Microsoft.AspNetCore.Mvc.Controller c) => c.HttpContext._GetRequestCancellationToken();
Exemplo n.º 29
0
 /// <summary>
 /// Gets the current Audit Scope.
 /// </summary>
 /// <param name="apiController">The API controller.</param>
 /// <returns>The current Audit Scope or NULL.</returns>
 public static AuditScope GetCurrentAuditScope(this Microsoft.AspNetCore.Mvc.Controller apiController)
 {
     return(AuditApiAdapter.GetCurrentScope(apiController.HttpContext));
 }
Exemplo n.º 30
0
 public static dynamic GetCurrent(this Microsoft.AspNetCore.Mvc.Controller controller)
 {
     return(Get(controller.ControllerContext.RouteData.Values["controller"].ToString()));
 }