/// <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)); }
/// <summary> /// Formats postive responses from UseCases into APIResponses /// </summary> /// <typeparam name="T"></typeparam> /// <param name="controller"></param> /// <param name="result"></param> /// <returns></returns> public static IActionResult StandardResponse <T>(this Microsoft.AspNetCore.Mvc.Controller controller, T result) where T : class { var apiResponse = new APIResponse <T>(result); //Use Extension Method to set a statusCode as well as an object return(controller.StatusCode(apiResponse.StatusCode, apiResponse)); }
/// <summary> /// 创建控制器之后的回调方法; /// </summary> /// <param name="result"></param> /// <returns></returns> private IController ActionWhenCreateController(IController result) { if (result is AbstractMvcControllerWithDbContext <K> ) { var bc = ((AbstractMvcControllerWithDbContext <K>)result); //允许对控制器进行跨域的调用; //var Response = requestContext.HttpContext.Response; // //Response.ClearContent(); //清除内容,应该无用,因为刚刚创建的控制器应该肯定没有内容 // Response.AddHeader("Access-Control-Allow-Origin", "*"); //使用 IIS 的配置: // Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); // Response.AddHeader("Access-Control-Allow-Headers", "*"); if (AbstractMvcControllerWithDbContext <K> .ThreadLocal.Value == null) //使用相同的 DbContext; { bc.DbContext = dbContextFactory(); AbstractMvcControllerWithDbContext <K> .ThreadLocal.Value = bc.DbContext; } else { bc.DbContext = AbstractMvcControllerWithDbContext <K> .ThreadLocal.Value; } bc.Activate(); } if (this.controlAction != null) { controlAction(result); } return(result); }
/// <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)); }
// Add a mock identity claim to the controller context public static void AddMockIdentityToContext(Microsoft.AspNetCore.Mvc.Controller controller, string identity) { controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext.User = new ClaimsPrincipal(); controller.ControllerContext.HttpContext.User.AddIdentity(new ClaimsIdentity()); ((ClaimsIdentity)controller.ControllerContext.HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Name, identity)); }
//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 }
public static IActionResult LoadingPage(this Microsoft.AspNetCore.Mvc.Controller controller, string viewName, string redirectUri) { controller.HttpContext.Response.StatusCode = 200; controller.HttpContext.Response.Headers["Location"] = ""; return(controller.View(viewName, new RedirectViewModel { RedirectUrl = redirectUri })); }
public static IActionResult AccessDenied(this Mvc.Controller controller) { if (controller == null) { throw new ArgumentNullException(nameof(controller)); } return(new AccessDeniedResult(controller.User)); }
public static void SetUserIsAuthenticated(this Microsoft.AspNetCore.Mvc.Controller controller, bool isAuthenticated) { var mockContext = new Mock <HttpContext>(); mockContext.SetupGet(context => context.User.Identity.IsAuthenticated).Returns(isAuthenticated); controller.ControllerContext = new ControllerContext { HttpContext = mockContext.Object }; }
/// <summary> /// /// </summary> /// <param name="stream"></param> /// <param name="controller"></param> public MyPDFResult(Stream stream, ApiController controller) : base("application/pdf") { this.Stream = stream; #if !NET461 #else this.ApiController = controller; controller.ControllerContext.ControllerDescriptor.Properties[Controllers.BasicController.HttpResponseTag] = this; #endif }
public static ActionResult GetODataServiceDocumentJsonV4( this Microsoft.AspNetCore.Mvc.Controller ctrl, TableSpec[] tables, string MetadataPath) { ctrl.Response.Headers.Add("OData-Version", "4.0"); return(ctrl.Content(ODataHandler.GetRootMetadataJsonV4( ctrl.Request.Scheme + "://" + ctrl.Request.Host + "/" + MetadataPath, tables), "application/json; odata.metadata=minimal")); }
/// <summary> /// /// </summary> /// <param name="stream"></param> /// <param name="controller"></param> public MyExcelResult(Stream stream, ApiController controller) : base("text/xls") { this.Stream = stream; #if !NET461 #else this.ApiController = controller; controller.ControllerContext.ControllerDescriptor.Properties[BasicController.HttpResponseTag] = this; #endif }
protected void ProtectsFromOverpostingId(Controller controller, String postMethod) { MethodInfo methodInfo = controller .GetType() .GetMethods() .First(method => method.Name == postMethod && method.IsDefined(typeof(HttpPostAttribute), false)); Assert.NotNull(methodInfo.GetParameters()[0].IsDefined(typeof(BindExcludeIdAttribute), false)); }
public static ActionResult GetODataMetadataXmlV4( this Microsoft.AspNetCore.Mvc.Controller ctrl, TableSpec[] tables, string ModelNamespace = null) { if (string.IsNullOrWhiteSpace(ModelNamespace)) { ModelNamespace = ctrl.ControllerContext.ActionDescriptor.ControllerName + ".Models"; } ctrl.Response.Headers.Add("OData-Version", "4.0"); // Probably not nessecary but someone might need it as root. return(ctrl.Content(ODataHandler.GetMetadataXmlV4(tables, ModelNamespace), "application/xml")); }
public static RequestHandler Table( this Microsoft.AspNetCore.Mvc.Controller ctrl, TableSpec tableSpec) { var querySpec = TSql.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)); }
/// <summary> /// 释放控制器时候的回调; /// </summary> /// <param name="controller"></param> private void ActionWhenReleaseController(IController controller) { if (controller is AbstractMvcControllerWithDbContext <K> ) { var bc = ((AbstractMvcControllerWithDbContext <K>)controller); bc.Deactivate(); if (bc.DbContext != null) { bc.DbContext.Dispose(); bc.DbContext = null; } } }
// pretend a User // a helper method for testing purposes public static void MockUser(this Microsoft.AspNetCore.Mvc.Controller controller, string userId, string userName) { var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName) })); controller.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = user } }; }
/// <summary> /// Initializes a new instance of the <see cref="MyJsonResult{T}"/> class. /// </summary> /// <param name="content"></param> /// <param name="controller">The controller.</param> /// <param name="encoding">The encoding.</param> /// <param name="jsonSerializer"></param> public MyJsonResult(T content, ApiController controller, IJsonSerializer jsonSerializer, Encoding encoding) { #if !NET461 this.request = new HttpRequestMessage(new HttpMethod(controller.Request.Method), controller.Request.PathBase.Value); this.encoding = encoding; this.content = content; this.jsonSerializer = jsonSerializer; #else this.ApiController = controller; this.request = new HttpRequestMessage(controller.Request.Method, controller.Request.RequestUri); this.encoding = encoding; this.content = content; this.jsonSerializer = jsonSerializer; controller.ControllerContext.ControllerDescriptor.Properties[BasicController.HttpResponseTag] = this; #endif }
public async Task AddOrUpdateRepresentationAsync( Controller controller, string representationId) { if (controller == null) { throw new ArgumentNullException(nameof(controller)); } if (string.IsNullOrWhiteSpace(representationId)) { throw new ArgumentNullException(nameof(representationId)); } var concurrentObject = await _concurrencyManager.TryUpdateRepresentationAsync(representationId); SetHeaders(controller, concurrentObject); }
public PageViewModel(Controller context) { ContainerName = "Page"; ControllerName = context.RouteData.Values["controller"].ToString(); Action = context.RouteData.Values["action"].ToString(); /* Action = actionContext.ActionDescriptor.Name; ControllerName = actionContext.RouteData.Values["controller"].ToString(); */ NestedView = this.Action; }
public static void SetAjaxRequest(this Microsoft.AspNetCore.Mvc.Controller controller, bool isAjax) { var mockContext = new Mock <HttpContext>(); if (isAjax) { mockContext.SetupGet(c => c.Request.Headers["X-Requested-With"]).Returns("XMLHttpRequest"); } else { mockContext.SetupGet(c => c.Request.Headers["X-Requested-With"]).Returns(""); } controller.ControllerContext = new ControllerContext { HttpContext = mockContext.Object }; }
public async Task<bool> CheckRepresentationExistsAsync( Controller controller, string representationId) { if (controller == null) { throw new ArgumentNullException(nameof(controller)); } if (string.IsNullOrWhiteSpace(representationId)) { throw new ArgumentNullException(nameof(representationId)); } var concatenatedEtags = controller.GetIfMatch(); var unmodifiedSince = controller.GetUnmodifiedSince(); var checkDateCallback = new Func<DateTime, ConcurrentObject, bool>((d, c) => { return c.DateTime <= d; }); var checkEtagCorrectCallback = new Func<ConcurrentObject, List<EntityTagHeaderValue>, bool>((c, etags) => { return etags.Any(e => { if (e.IsWeak) { // Weak etag if (c.Etag.Contains(e.Tag)) { return true; } } else { if (e.Tag == c.Etag) { return true; } } return false; }); }); return await ContinueExecution(concatenatedEtags, unmodifiedSince, representationId, checkDateCallback, checkEtagCorrectCallback); }
public static ActionResult GetODataServiceDocumentJsonV4( this Microsoft.AspNetCore.Mvc.Controller ctrl, TableSpec[] tables, Func <ActionResult> MetadataAction) { var mi = MetadataAction.GetMethodInfo(); var httpAttr = Attribute.GetCustomAttribute(mi, typeof(HttpGetAttribute)) as HttpGetAttribute; if (httpAttr == null) { throw new InvalidOperationException($"Action {mi.Name} must have [HttpGet] attribute"); } if (string.IsNullOrWhiteSpace(httpAttr.Template)) { throw new InvalidOperationException($"Action {mi.Name} don't have template in [HttpGet(<template>)] atttribute."); } var url = httpAttr.Template .Replace("[controller]", ctrl.GetType().Name.Replace("Controller", "")) .Replace("[action]", mi.Name); return(GetODataServiceDocumentJsonV4(ctrl, tables, url)); }
public static ViewResult GetView(this Microsoft.AspNetCore.Mvc.Controller ctrl, [CallerMemberName] string name = "", object model = null) { name = GetLastMethodName(name); if (InvocationHub.IsModuleInDebugMode()) { return(ctrl.View(name, model)); } else { var mdlName = ctrl.ControllerContext.HttpContext.Items[Consts.CONTEXT_ITEM_KEY_THEME_MODULE_NAME].ToString(); var controllerName = ctrl.GetType().Name.Replace("Controller", "", StringComparison.OrdinalIgnoreCase); var path = $"{Consts.MODULES_BASE_PATH}\\{mdlName}\\Views\\{controllerName}\\"; var file = ""; try { file = Directory.GetFiles(path, $"{name}.*").Single(); } catch (FileNotFoundException) { throw new ViewFileNotFoundException(mdlName, controllerName, name); } return(ctrl.View($"~/{path.Replace("\\","/")}{new FileInfo(file).Name}", model)); } }
public static IActionResult ExecuteStandardResponse <T>(this Microsoft.AspNetCore.Mvc.Controller controller, IExecuteWrapper <T> result) where T : class { var apiResponse = new APIResponse <T>(result); return(controller.StatusCode(apiResponse.StatusCode, apiResponse)); }
private static void SetFakeHttpContextIfNotAlreadySet(Controller controller) { if (controller.ControllerContext.HttpContext == null) controller.ControllerContext.HttpContext = FakeHttpContext(); }
public static CancellationToken _GetRequestCancellationToken(this Microsoft.AspNetCore.Mvc.Controller c) => c.HttpContext._GetRequestCancellationToken();
public EditViewModel(Controller context) : base(context) { var deplural = depluralizeController(ControllerName) ?? ControllerName; Title = deplural; Description = $"A form for editing the data for this, {deplural}"; }
/* public string CreateEditPath { get { return ($"~/Views/{ControllerName}/{CreateEditFieldset}.cshtml"); } } */ /* public override string NestedViewPath { get { return ($"~/Views/{ContainerFolder}/{NestedView}Container.cshtml"); } } */ public CreateEditViewModel(Controller context) : base(context) { ContainerName = BasicMvc+CreateEditFieldset; NestedView = CreateEditFieldset; }
public IndexViewModel(Controller context) : base(context) { ContainerName = BasicMvc + IndexContainer; Title = ControllerName; Description = $"All {ControllerName} in the Database"; }
private void SetHeaders(Controller controller, ConcurrentObject concurrentObject) { controller.SetEtag(concurrentObject.Etag); controller.SetLastModifiedDate(concurrentObject.DateTime.ToUniversalTime().ToString("R")); }
public async Task<bool> CheckRepresentationHasChangedAsync( Controller controller, string representationId) { if (controller == null) { throw new ArgumentNullException(nameof(controller)); } if (string.IsNullOrWhiteSpace(representationId)) { throw new ArgumentNullException(nameof(representationId)); } // Check the http request contains the header "If-None-Match" var concatenatedEtags = controller.GetIfNoneMatch(); var modifiedSince = controller.GetModifiedSince(); var checkDateCallback = new Func<DateTime, ConcurrentObject, bool>((d, c) => { return c.DateTime > d; }); var checkEtagCorrectCallback = new Func<ConcurrentObject, List<EntityTagHeaderValue>, bool>((c, etags) => { return etags.All(etag => { if (etag.IsWeak) { // Weak etag if (c.Etag.Contains(etag.Tag)) { return false; } } else { if (etag.Tag == c.Etag) { return false; } } return true; }); }); return await ContinueExecution(concatenatedEtags, modifiedSince, representationId, checkDateCallback, checkEtagCorrectCallback); }
/// <summary> /// 控制器释放时候的钩子方法; /// </summary> /// <param name="controller"></param> public override void ReleaseController(IController controller) { ActionWhenReleaseController(controller); base.ReleaseController(controller); }
public static ViewResult View(this Microsoft.AspNetCore.Mvc.Controller ctrl, [CallerMemberName] string name = "", object model = null) { return(ctrl.GetView(name, model)); }
public static JsonResult BuildDataTableForm <T>(this Microsoft.AspNetCore.Mvc.Controller controller, List <T> data) { // Initialization. string search = controller.Request.Form["search[value]"][0]; string draw = controller.Request.Form["draw"][0]; string order = controller.Request.Form["order[0][column]"][0]; string orderDir = controller.Request.Form["order[0][dir]"][0]; int startRec = Convert.ToInt32(controller.Request.Form["start"][0]); int pageSize = Convert.ToInt32(controller.Request.Form["length"][0]); // Total record count. int totalRecords = data.Count; // Verification. if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search)) { // Apply search var tempData = new List <T>(); foreach (var item in typeof(T).GetProperties()) { if (item.PropertyType.Name != typeof(List <>).Name) { tempData.AddRange(data.Where(m => { return(m.GetType().GetProperty(item.Name).GetValue(m, null).ToString().ToLower().Contains(search.ToLower())); })); } } data = tempData.Distinct().ToList(); } // Sorting. var orderField = controller.Request.Form["columns[" + order + "][data]"][0]; data = SortByColumnWithOrder(orderField, orderDir, data); // Filter record count. int recFilter = data.Count; // Apply pagination. data = data.Skip(startRec).Take(pageSize).ToList(); var finalData = new List <Dictionary <string, object> >(); foreach (var item in data) { //TODO: When you add a new data formatting here, make sure to add also in dataTable.js Ln 24 var expObj = new Dictionary <string, object>(); foreach (var p in item.GetType().GetProperties()) { expObj.Add(p.Name.ToCamelCase(), p.GetValue(item)); if (p.PropertyType.BaseType == typeof(Enum)) { expObj.Add(p.Name.ToCamelCase() + "Desc", p.GetValue(item).ToString()); } else if (p.PropertyType == typeof(DateTimeOffset)) { expObj.Add(p.Name.ToCamelCase() + "Desc", DateTime.Parse(p.GetValue(item).ToString()).ToString("MMM d, yyyy HH:mm:ss")); } } finalData.Add(expObj); } // Loading drop down lists. var result = controller.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = finalData }); return(result); }
public DetailsViewModel(Controller context): base(context) { ContainerName = BasicMvc + DetailsContainer; var deplural = depluralizeController(ControllerName) ?? ControllerName; Title = deplural; Description = $"All the data for this, {deplural}"; }
/// <summary> /// Initializes a new instance of the <see cref="MyJsonResult{T}"/> class. /// </summary> /// <param name="content"></param> /// <param name="controller">The controller.</param> public MyJsonResult(T content, ApiController controller) : this(content, controller, Never.Serialization.SerializeEnvironment.JsonSerializer, new UTF8Encoding(false, true)) { }
public CreateViewModel(Controller context) : base(context) { var deplural = depluralizeController(ControllerName) ?? ControllerName; Title = deplural; Description = $"Create a new, {deplural}"; }
/// <summary> /// Initializes a new instance of the <see cref="MyJsonResult{T}"/> class. /// </summary> /// <param name="content"></param> /// <param name="controller">The controller.</param> /// <param name="jsonSerializer"></param> public MyJsonResult(T content, ApiController controller, IJsonSerializer jsonSerializer) : this(content, controller, jsonSerializer, new UTF8Encoding(false, true)) { }
public DeleteViewModel(Controller context) : base(context) { ContainerName = BasicMvc + DeleteContainer; var deplural = depluralizeController(ControllerName) ?? ControllerName; Title = deplural; Description = $"Are you sure you want to delete this {deplural}?"; }
public static Microsoft.AspNetCore.Mvc.JsonResult ToJsonSuccess(this object obj, Microsoft.AspNetCore.Mvc.Controller controller) { return(controller.JsonSuccess(new JsonResponse1 <object> { JsonData = obj })); }
public BasicViewModel(Controller context) : base(context) { }
private static void MakeUserOrganizationAdminUser(Controller controller, string organizationId) { var orgAdminClaims = new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, Enum.GetName(typeof(UserType), UserType.OrgAdmin)), new Claim(AllReady.Security.ClaimTypes.Organization, organizationId) }; var httpContext = new Mock<HttpContext>(); var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(orgAdminClaims)); httpContext.Setup(x => x.User).Returns(claimsPrincipal); controller.ControllerContext.HttpContext = httpContext.Object; }