public void ExecuteResult() { // Arrange string content = "Some content."; string contentType = "Some content type."; Encoding contentEncoding = Encoding.UTF8; // Arrange expectations Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict); mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable(); mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable(); mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable(); ContentResult result = new ContentResult { Content = content, ContentType = contentType, ContentEncoding = contentEncoding }; // Act result.ExecuteResult(mockControllerContext.Object); // Assert mockControllerContext.Verify(); }
public void AllPropertiesDefaultToNull() { // Act ContentResult result = new ContentResult(); // Assert Assert.IsNull(result.Content); Assert.IsNull(result.ContentEncoding); Assert.IsNull(result.ContentType); }
protected new ActionResult Json(object data, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet) { var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; if (Request.RequestType == WebRequestMethods.Http.Get && behavior == JsonRequestBehavior.DenyGet) { throw new InvalidOperationException("GET is no permitted for this request"); } var jsonResult = new ContentResult { Content = JsonConvert.SerializeObject(data, jsonSerializerSettings), ContentType = "application/json" }; return(jsonResult); }
public static async Task <IActionResult> RenderSwaggerUI( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "swagger")] HttpRequest request, ILogger log) { var ui = new SwaggerUI(); var result = await ui.AddMetadata(GetOpenApiInfo()) .AddServer(request, "api") .BuildAsync() .RenderAsync("openapi/json", null) .ConfigureAwait(false); var response = new ContentResult() { Content = result, ContentType = "text/html", StatusCode = (int)HttpStatusCode.OK }; return(response); }
public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.ModelState.IsValid) { var result = new ContentResult(); var errors = new Dictionary <string, string[]>(); foreach (var valuePair in filterContext.ModelState) { errors.Add(valuePair.Key, valuePair.Value.Errors.Select(x => x.ErrorMessage).ToArray()); } string content = JsonConvert.SerializeObject(new { errors }); result.Content = content; result.ContentType = "application/json"; filterContext.HttpContext.Response.StatusCode = 422; //unprocessable entity; filterContext.Result = result; } }
/// <summary> /// 没有登录 /// </summary> /// <returns>ActionResult.</returns> public ActionResult Http401() { string message = RouteData.Values["exception"].ToString(); bool isAjax = Request.Headers["x-requested-with"] == null ? false : true;//判断是否ajax请求 if (!isAjax) { Response.Redirect("/Login.html"); Response.End(); //return Redirect("/Login.html"); } Response.Charset = "utf-8"; ContentResult res = new ContentResult() { Content = JSON.ToJSON(new JSResponse("401", message), jsonParams) }; return(res); }
//18.Year and Month Multiplication public ActionResult CalculateTime1(int Month, int Multipli, int Year) { int result = Year * Multipli; int result2; for (result2 = Month * Multipli; result2 > 12; result2 = result2 - 12) { if ((result2 % 12) > 0) { result += 1; } } string resultString = "year=" + result.ToString() + " month=" + result2.ToString(); ContentResult test = new ContentResult(); test.Content = resultString; return(test); }
//16.Time Multiplication public ActionResult CalculateTe(int hour, int minute, int Multipli) { int result = hour * Multipli; int result2; for (result2 = minute * Multipli; result2 > 60; result2 = result2 - 60) { if ((result2 % 60) > 0) { result += 1; } } string resultString = "Hour=" + result.ToString() + " Minute=" + result2.ToString(); ContentResult test = new ContentResult(); test.Content = resultString; return(test); }
public async Task <ApiResponseModel <XDocument> > GetOsmDataByBbox([FromBody] BoundingBox boundingBox) { HttpClient client = _httpClientFactory.CreateClient(_config["MapApiName"]); string url = $"{client.BaseAddress}/map?bbox={boundingBox.MinimumLongitude},{boundingBox.MinimumLatitude},{boundingBox.MaximumLongitude},{boundingBox.MaximumLatitude}"; using HttpResponseMessage responseMessage = await client.GetAsync(url); ContentResult result = Content(await responseMessage.Content.ReadAsStringAsync(), "text/xml"); return((ApiResponseModel <XDocument>)(new() { StatusCode = responseMessage.StatusCode, Result = responseMessage.IsSuccessStatusCode ? XDocument.Parse(result.Content) : null, Message = responseMessage.IsSuccessStatusCode ? null : result.Content })); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var cName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; var action = filterContext.ActionDescriptor.ActionName; if (cName != "Account" && action != "Index")//cName != "Account" && action != "Login" { var returnUlr = filterContext.HttpContext.Request.Url.AbsolutePath; var redirectUrl = string.Format("?ReturnUrl={0}", returnUlr); var loginUrl = FormsAuthentication.LoginUrl + redirectUrl; if (!HttpContext.Current.User.Identity.IsAuthenticated) { Logon(filterContext); } else { //角色校验: if (Code != 0) { var emType = Enum.Parse(typeof(SysRoleEnum.RoleEnum), Code.ToString());//通关角色编号获取角色名称 bool isAuthenticated = filterContext.HttpContext.User.IsInRole(emType.ToString()); if (!isAuthenticated) { ContentResult ctRes = new ContentResult(); var errorUrl = "~/Shared/Error"; ctRes.Content = string.Format("<script type='text/javascript'>alert('你无权限执行该操作!');window.location.href='{0}';</script>", errorUrl);//返回错误页 filterContext.Result = ctRes; //throw new UnauthorizedAccessException("You have no right to view this page!"); } } else { //没配置权限?按需进行逻辑操作: //throw new InvalidOperationException("No Role Specified!"); } } } base.OnActionExecuting(filterContext); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var cacheSettings = context.HttpContext.RequestServices.GetRequiredService <RedisCacheSettings>(); if (!cacheSettings.Enabled) { await next(); return; } var cacheService = context.HttpContext.RequestServices.GetRequiredService <ICacheService>(); var cacheKey = GenerateCacheKeyFromRequest(context.HttpContext.Request); var cachedResponse = await cacheService.GetCachedResponseAsync(cacheKey); if (!string.IsNullOrEmpty(cachedResponse)) { var contentResult = new ContentResult { Content = cachedResponse, ContentType = "application/json", StatusCode = 200 }; context.Result = contentResult; return; } var executedContext = await next(); if (executedContext.Result is OkObjectResult okObjectResult) { DefaultContractResolver contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; var value = JsonConvert.SerializeObject(okObjectResult.Value, new JsonSerializerSettings { ContractResolver = contractResolver, Formatting = Formatting.Indented }); await cacheService.CacheResponseAsync(cacheKey, JsonConvert.DeserializeObject(value), TimeSpan.FromSeconds(_timeToLiveSeconds)); } }
public async Task <JsonResult> SearchGeoJsonFeaturesByCoordinates(OpenStreetMapViewModel openStreetMapViewModel) { OsmApiResponseModel osmApiResponseModel = new(); if (ModelState.IsValid) { HttpClient client = _httpClientFactory.CreateClient(_config["MapApiName"]); string url = $"{client.BaseAddress}/GeoJsonFeatures/GetOsmDataByBbox"; HttpRequestMessage request = new() { Method = HttpMethod.Get, RequestUri = new Uri(url), Content = new StringContent(JsonConvert.SerializeObject(openStreetMapViewModel), Encoding.UTF8, "application/json") }; using HttpResponseMessage response = await client.SendAsync(request); ContentResult responseResult = Content(await response.Content.ReadAsStringAsync(), "text/xml"); osmApiResponseModel = JsonConvert.DeserializeObject <OsmApiResponseModel>(responseResult.Content); if (osmApiResponseModel.StatusCode != HttpStatusCode.OK) { HttpContext.Response.StatusCode = (int)osmApiResponseModel.StatusCode; return(Json(osmApiResponseModel)); } } else { HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; osmApiResponseModel.Message = string.Join("<br/>", ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage)) .ToList() ); return(Json(osmApiResponseModel)); } return(Json(osmApiResponseModel.Result.ToString())); }
public ContentResult Create(simpleSystem.ViewModels.OrderCreateViewModels createModel) { OrderService orderService = new OrderService(); Models.Order ModelOrder = new Models.Order { OrderID = createModel.OrderID, CustomerID = createModel.CustID, EmployeeID = createModel.EmpId, Freight = (decimal)createModel.Freight, OrderDate = (DateTime)createModel.OrderDate, RequiredDate = (DateTime)createModel.RequiredDate, ShipAddress = createModel.ShipAddress, ShipCity = createModel.ShipCity, ShipCountry = createModel.ShipCountry, ShipName = createModel.ShipName, ShippedDate = createModel.ShippedDate, ShipperID = createModel.ShipperId, ShipPostalCode = createModel.ShipPostalCode, ShipRegion = createModel.ShipRegion, OrderDetails = new HashSet <Models.OrderDetail>() }; int sum = 0; foreach (var tmp in createModel.ProductID) { ModelOrder.OrderDetails.Add(new Models.OrderDetail { ProductID = createModel.ProductID[sum], Qty = (short)createModel.Qty[sum], UnitPrice = (decimal)createModel.UnitPrice[sum] }); sum = sum + 1; } orderService.InsertOrder(ModelOrder); ContentResult result = new ContentResult(); result.Content = "新增成功"; return(result); }
public void OnAuthorization_RedirectsToAuthorizationRedirectPath_OnlyWhenUserDeniedGrantingPermissions( string requestUrl, string expectedRedirectUrl ) { FacebookClient client = MockHelpers.CreateFacebookClient(); IFacebookPermissionService permissionService = MockHelpers.CreatePermissionService( new[] { "" } ); FacebookConfiguration config = MockHelpers.CreateConfiguration( client, permissionService ); config.AuthorizationRedirectPath = "~/home/permissions"; FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config); AuthorizationContext context = new AuthorizationContext( MockHelpers.CreateControllerContext( new NameValueCollection { { "signed_request", "exampleSignedRequest" } }, null, new Uri(requestUrl) ), MockHelpers.CreateActionDescriptor( new[] { new FacebookAuthorizeAttribute("email") } ) ); authorizeFilter.OnAuthorization(context); ContentResult result = Assert.IsAssignableFrom <JavaScriptRedirectResult>( context.Result ); Assert.Equal("text/html", result.ContentType); Assert.Equal( String.Format("<script>window.top.location = '{0}';</script>", expectedRedirectUrl), result.Content ); }
public void OnAuthorization(AuthorizationContext filterContext) { if (!filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) { VModel.SyPassport.UserInfo userInfo = filterContext.HttpContext.Session["UserInfo"] as VModel.SyPassport.UserInfo; if (userInfo == null) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { ContentResult cr = new ContentResult(); cr.Content = "<p style=\"padding:30px 0 30px 0;text-align:center\">你的账号已经下线了请回到首页</p><p style=\"text-align:center;margin:10px 0 20px 0;\"><a href=\"/SyPassport/Login\" style=\"display:inline-block;width:80px;height:30px;line-height:30px;background-color:#36aa9d;color:#fff;text-align:center;\">重新登录</a></p>"; cr.ContentType = "application/x-javascript"; filterContext.Result = cr; } else { filterContext.Result = new RedirectResult("/SyPassport/Login"); } } } }
// список страниц public IActionResult Index(int?id) { #region debug core string conn = ConfigurationManager.AppSettings["conn"]; ContentResult cr = new ContentResult(); cr.Content = conn; //return cr; #endregion PageServices pageServices = new PageServices(); IndexViewModel VM = new IndexViewModel(); VM.selectedCat_ID = id; VM.webRoot = _env.WebRootPath; VM.pageCategories = pageServices.GetPageCategories().ToList(); VM.pages = pageServices.GetPages(id); return(View(VM)); }
public void OnAuthorization_RedirectsToOAuthDialog_WhenSignedRequestIsNull() { FacebookConfiguration config = MockHelpers.CreateConfiguration(); FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config); AuthorizationContext context = new AuthorizationContext( MockHelpers.CreateControllerContext(), MockHelpers.CreateActionDescriptor( new[] { new FacebookAuthorizeAttribute("email") } ) ); authorizeFilter.OnAuthorization(context); ContentResult result = Assert.IsType <JavaScriptRedirectResult>(context.Result); Assert.Equal("text/html", result.ContentType); Assert.Equal( "<script>window.top.location = 'https://www.facebook.com/dialog/oauth?redirect_uri=https%3A%2F%2Fapps.facebook.com%2FDefaultAppId%2F\\u0026client_id=DefaultAppId';</script>", result.Content ); }
public override void OnActionExecuting(ActionExecutingContext actionContext) { if (actionContext.HttpContext.Request.HttpMethod.ToUpper() != "GET") { var data = new ServiceResponse { Status = "GetRequestExpected", MessageKey = MessageKey }; var response = data.ToJson(); var result = new ContentResult(); result.ContentType = "application/json"; result.ContentEncoding = Encoding.UTF8; result.Content = response; actionContext.Result = result; } else { base.OnActionExecuting(actionContext); } }
public void WithStatusCode_Throws_When_StatusCode_Is_Not_As_Expected() { // Arrange var target = new ContentResult { StatusCode = 100, }; var sut = new ContentResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithStatusCode(StatusCodes.Status200OK, "FOO {0}", "BAR")) .Should() .Throw <XunitException>() .WithMessage(@"Expected status code to be 200 because FOO BAR, but found 100."); sut.Invoking(x => x.WithStatusCode(HttpStatusCode.OK, "FOO {0}", "BAR")) .Should() .Throw <XunitException>() .WithMessage(@"Expected status code to be 200 because FOO BAR, but found 100."); }
public ContentResult Update() { var result = new ContentResult(); try { FillChartData(_diagramId, -1, -1, _userId); var states = (List <String>)ViewBag.DataStates; result.ContentType = "application/json"; result.Content = string.Join(" ", states); return(result); } catch (Exception e) { ExceptionMessageToViewBag(e); result.ContentType = "text/plain"; result.Content = "Exception: " + e.Message; return(result); } }
public ActionResult LoadBelongOrg4dhtmlxTree() { IList <UserManageDepartModel> departList = new List <UserManageDepartModel>(); if (LoginHelper.LoginUserAuthorize.Contains("Instrument-CheckAll".ToLower()) || LoginHelper.LoginUserAuthorize.Contains("Instrument-SearchCheckAll".ToLower())) { departList = ServiceProvider.UserManageDepartService.GetAll(); } else { departList = LoginHelper.LoginUser.manageDepartList; } IList <OrgModel> orgList = ServiceProvider.OrgService.GetByOrgIds(departList.Select(d => d.OrgId).ToList()); ContentResult cr = new ContentResult(); cr.ContentType = "text/xml"; cr.ContentEncoding = Encoding.UTF8; cr.Content = ServiceProvider.OrgService.GetParentdhtmlxTree(orgList); return(cr); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { int eventtype = (int)filterContext.ActionParameters["EventType"]; DesignEventType designeventtype = new DesignEventType(); if (eventtype == 1) { if (System.DateTime.Now >= siteEndTime) { object data = null; var obj = new { Code = 90, Message = "活动已结束", Data = data }; ContentResult result = new ContentResult(); string json = JsonConvert.SerializeObject(obj); string jsonp = filterContext.HttpContext.Request["jsonpcallback"]; string returnString = jsonp + "(" + json + ")"; result.Content = returnString; filterContext.Result = result; } } }
private static void ToUrl(ActionExecutingContext filterContext) { //获取当前方法是否有ajax标签 bool isAjax = filterContext.ActionDescriptor.IsDefined(typeof(AjaxRequestAttribute), false); if (isAjax) { //2.0.1如果是ajax请求,应该返回Json JsonResult json = new JsonResult(); json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; json.Data = new { status = Enums.EStateType.nologin, msg = "您未登录", loginurl = "/Admin/Login/Login" }; filterContext.Result = json; } else { //2.0.2 如果是浏览器请求则直接将Url到登录页面 ContentResult content = new ContentResult(); content.Content = "<script>alert('您未登录');window.location='/Admin/Login/Login';</script>"; filterContext.Result = content; } }
/// <summary> /// 校验开关账状态(仅限当月) /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { string propertyId = Utils.GetCookie("property_id"); bool fstatus = feeclosebll.GetCurrentStatus(propertyId); if (!fstatus) { string requestType = filterContext.HttpContext.Request.RequestType.ToLower(); if (requestType.Equals("post")) { ContentResult Content = new ContentResult(); //Content.Content = "<script type='text/javascript'>alert('很抱歉!财务账单被关闭,操作被拒绝!');top.Loading(false);</script>"; Content.Content = new AjaxResult { type = ResultType.error, message = "很抱歉!财务账单被关闭,操作被拒绝!" }.ToJson(); filterContext.Result = Content; return; } } }
private void DoRedirect(AuthenticationContext filterContext) { if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { var result = new JsonResult(); result.Data = new { success = false, msg = "您没有权限", jump = true }; result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; filterContext.Result = result; } else { var result = new ContentResult(); result.Content = "<script>alert('您没有权限')</script>"; filterContext.Result = result; } }
/// <summary> /// 权限错误,页面跳转处理 /// </summary> /// <param name="filterContext"></param> /// <param name="type"></param> public void TransferToPermissionDeniedPage(ActionExecutingContext filterContext, int type = 1) { ContentResult result = new ContentResult(); switch (type) { case 1: result.Content = "<script>window.location.href='/Home/LoginTimeout';</script>"; _session.RemoveAll(); _session.Abandon(); break; case 2: result.Content = "<script>window.location.href='/Home/NoPermission';</script>"; break; default: result.Content = "<script>window.location.href='/Home/Sorry';</script>"; _session.RemoveAll(); _session.Abandon(); break; } filterContext.Result = result; }
public async Task <ActionResult> GetVariables() { if (Request.Cookies["session"] == null) { return(StatusCode(400)); } User user = SessionManager.Authenticate(Request.Cookies["session"]); Console.WriteLine(Request.Cookies["session"]); if (user == null) { return(StatusCode(403)); } ContentResult content = new ContentResult(); content.Content = JsonConvert.SerializeObject(user.session_vars); content.ContentType = "application/json"; Console.WriteLine($"Real: {string.Join("", user.session_vars)}"); Console.WriteLine($"Fake: {content.Content.ToString()}"); return(content); }
/// <summary> /// 生成JS消息 /// </summary> /// <param name="msg">消息</param> /// <param name="backUrl">url</param> /// <returns></returns> public ContentResult JsMsg(string msg, string backUrl) { StringBuilder sb = new StringBuilder(); sb.Append("<script>alert('" + msg + "');"); if (!backUrl.IsNullOrEmpty()) { sb.Append("if(window.top)"); sb.Append(" window.top.location.href='" + backUrl + "';"); sb.Append("else"); sb.Append(" window.location.href='" + backUrl + "';"); } sb.Append("</script>"); ContentResult content = new ContentResult() { Content = sb.ToString(), ContentType = "text/html" }; return(content); }
public override Task OnExceptionAsync(ExceptionContext context) { var exception = context.Exception; if (RewriteErrors) { var rewriter = context.HttpContext.RequestServices.GetRequiredService <IErrorRewriter>(); exception = rewriter.Rewrite(context, exception, true); } var serializer = new JsonNetSerializer(JsonNetSerializer.DefaultSettings); var content = serializer.Serialize(exception); var result = new ContentResult() { Content = content, ContentType = "application/json", StatusCode = (int)HttpStatusCode.InternalServerError, }; context.ExceptionHandled = true; return(result.ExecuteResultAsync(context)); }
public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.ModelState.IsValid) { if (filterContext.HttpContext.Request.Method == "GET") { var result = new BadRequestResult(); filterContext.Result = result; } else { var result = new ContentResult(); string content = Helpers.JsonSerialize(new ApiError(filterContext.ModelState)); result.Content = content; result.ContentType = "application/json"; filterContext.HttpContext.Response.StatusCode = 400; filterContext.Result = result; } } }
public ActionResult IndexTitle(int titleId) { ActionResult actionResult = null; try { BusinessLogic bl = new BusinessLogic(); bl.IndexTitle(titleId); actionResult = new ContentResult() { Content = string.Empty }; } catch (Exception ex) { HandleErrorInfo errorInfo = new HandleErrorInfo(ex, "titles", "IndexTitle"); actionResult = View("Error", errorInfo); } return(actionResult); }
/// <summary> /// 验证权限(action执行前会先执行这里) /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { //如果存在身份信息 if (!HttpContext.Current.User.Identity.IsAuthenticated) { ContentResult Content = new ContentResult(); Content.Content = string.Format("<script type='text/javascript'>alert('请先登录!');window.location.href='{0}';</script>", FormsAuthentication.LoginUrl); filterContext.Result = Content; } else { string[] Role = null; //CheckLogin.Instance.GetUser().Roles.Split(',');//获取所有角色 if (!Role.Contains(Code)) //验证权限 { //验证不通过 ContentResult Content = new ContentResult(); Content.Content = "<script type='text/javascript'>alert('权限验证不通过!');history.go(-1);</script>"; filterContext.Result = Content; } } }
public void BeContent_GivenContent_ShouldPass() { ActionResult result = new ContentResult(); result.Should() .BeContentResult(); }
private ContentCheckResult CheckContentResult(ContentResult origin, ContentResult input, Func<ContentResult, ContentResult, bool> contentResultStrategy) { return new ContentCheckResult { Input = input, Origin = origin, Passed = contentResultStrategy(origin, input), UID = input.UID }; }
public void NullContentIsNotOutput() { // Arrange string contentType = "Some content type."; Encoding contentEncoding = Encoding.UTF8; // Arrange expectations Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(); mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable(); mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable(); ContentResult result = new ContentResult { ContentType = contentType, ContentEncoding = contentEncoding }; // Act result.ExecuteResult(mockControllerContext.Object); // Assert mockControllerContext.Verify(); }
/// <summary> /// Initializes a new instance of the <see cref="T:ContentResultAssertions" /> class. /// </summary> public ContentResultAssertions(ContentResult subject) : base(subject) { }