public async Task ObjectResult_ExecuteResultAsync_SetsStatusCode()
        {
            // Arrange
            var result = new ObjectResult("Hello")
            {
                StatusCode = 404,
                Formatters = new List<IOutputFormatter>()
                {
                    new NoOpOutputFormatter(),
                },
            };

            var actionContext = new ActionContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    RequestServices = CreateServices(),
                }
            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(404, actionContext.HttpContext.Response.StatusCode);
        }
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var clientKeyString = actionContext.HttpContext.Request.Headers["ClientKey"];

            if (string.IsNullOrWhiteSpace(clientKeyString))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("ClientKey is not provided", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status403Forbidden;
                actionContext.Result = objectResult;
                return;
            }

            Guid clientKey = Guid.Empty;
            if(!Guid.TryParse(clientKeyString, out clientKey))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("ClientKey have bad format", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status403Forbidden;
                actionContext.Result = objectResult;
                return;
            }

            if(!_externalClientService.IsClientKeyValid(clientKey))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("ClientKey is not authorized", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status403Forbidden;
                actionContext.Result = objectResult;
            }
        }
        public IActionResult Delete(int id)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _removeResult = null;

            try
            {
                Photo _photoToRemove = this._photoRepository.GetSingle(id);
                this._photoRepository.Delete(_photoToRemove);
                this._photoRepository.Commit();

                _removeResult = new GenericResult()
                {
                    Succeeded = true,
                    Message = "Photo removed."
                };
            }
            catch (Exception ex)
            {
                _removeResult = new GenericResult()
                {
                    Succeeded = false,
                    Message = ex.Message
                };

                _loggingRepository.Add(new Error() { Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_removeResult);
            return _result;
        }
Exemple #4
0
        public async Task ObjectResult_WithMultipleContentTypesAndAcceptHeaders_PerformsContentNegotiation(
            IEnumerable<string> contentTypes, string acceptHeader, string expectedHeader)
        {
            // Arrange
            var expectedContentType = expectedHeader;
            var input = "testInput";
            var stream = new MemoryStream();

            var httpResponse = new Mock<HttpResponse>();
            var tempContentType = string.Empty;
            httpResponse.SetupProperty<string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object, acceptHeader);

            var result = new ObjectResult(input);

            // Set the content type property explicitly.
            result.ContentTypes = contentTypes.Select(contentType => MediaTypeHeaderValue.Parse(contentType)).ToList();
            result.Formatters = new List<IOutputFormatter>
                                            {
                                                new CannotWriteFormatter(),
                                                new JsonOutputFormatter(),
                                            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // should always select the Json Output formatter even though it is second in the list.
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);
        }
 public IActionResult OverrideTheFallback_UsingCustomFormatters(int input)
 {
     var objectResult = new ObjectResult(input);
     objectResult.Formatters.Add(new HttpNotAcceptableOutputFormatter());
     objectResult.Formatters.Add(new PlainTextFormatter());
     objectResult.Formatters.Add(new JsonOutputFormatter());
     return objectResult;
 }
        public IActionResult BadRequest(string errorMessage = "错误的请求")
        {
            var model = OperationResult.ErrorResult(errorMessage);

            var result = new ObjectResult(model);
            result.StatusCode = StatusCodes.Status400BadRequest;

            return result;
        }
        public IActionResult FatalError(string errorMessage = "服务器发生错误")
        {
            var model = OperationResult.ErrorResult(errorMessage);

            var result = new ObjectResult(model);
            result.StatusCode = StatusCodes.Status500InternalServerError;

            return result;
        }
            public void OnResourceExecuting(ResourceExecutingContext context)
            {
                var result = new ObjectResult("someValue");
                foreach (var formatter in _formatters)
                {
                    result.Formatters.Add(formatter);
                }

                context.Result = result;
            }
        public void GIVEN_AGoodAction_WHEN_Transform_THEN_Exception()
        {
            // Arrange
            var objectResult = new ObjectResult(new Post());

            // Act - Throw
            Assert.Throws<InvalidOperationException>(() => BadActionResultTransformer.Transform(objectResult));

            // Assert
        }
        public IActionResult FallbackGivesNoMatch(int input)
        {
            var objectResult = new ObjectResult(input);

            // Request content type is application/custom.
            // PlainTextFormatter cannot write because it does not support the type.
            objectResult.Formatters.Add(new PlainTextFormatter());

            return objectResult;
        }
        public IActionResult Post([FromBody]Todo value)
        {
            int maxId = sampleData.Max(t => t.Id);
            value.Id = maxId + 1;
            value.Completed = false;
            sampleData.Add(value);

            var result = new ObjectResult(value);
            result.StatusCode = (int)HttpStatusCode.Created;
            return result;
        }
        public IActionResult Add(AddCommentRequest model)
        {
            model.PostIP = this.Context.GetClientIP();

            var result = this.CommentService.Add(model);

            this.Response.Cookies.Append("comment_nickname", model.Nickname);
            this.Response.Cookies.Append("comment_email", model.Email);

            var or = new ObjectResult(result);
            return or;
        }
        public IActionResult OverrideTheFallback_WithDefaultFormatters(int input)
        {
            var objectResult = new ObjectResult(input);
            var formattersProvider = ActionContext.HttpContext.RequestServices.GetRequiredService<IOutputFormattersProvider>();
            objectResult.Formatters.Add(new HttpNotAcceptableOutputFormatter());
            foreach (var formatter in formattersProvider.OutputFormatters)
            {
                objectResult.Formatters.Add(formatter);
            }

            return objectResult;
        }
        public async Task<IActionResult> Login([FromBody] LoginViewModel user)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                Infrastructure.Services.MembershipContext _userContext = _membershipService.ValidateUser(user.Username, user.Password);

                if (_userContext.User != null)
                {
                    IEnumerable<Role> _roles = _userRepository.GetUserRoles(user.Username);
                    List<Claim> _claims = new List<Claim>();
                    foreach (Role role in _roles)
                    {
                        Claim _claim = new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, user.Username);
                        _claims.Add(_claim);
                    }
                    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(new ClaimsIdentity(_claims, CookieAuthenticationDefaults.AuthenticationScheme)),
                        new Microsoft.AspNet.Http.Authentication.AuthenticationProperties { IsPersistent = user.RememberMe });


                    _authenticationResult = new GenericResult()
                    {
                        Succeeded = true,
                        Message = "Authentication succeeded"
                    };
                }
                else
                {
                    _authenticationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message = "Authentication failed"
                    };
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message = ex.Message
                };

                _loggingRepository.Add(new Error() { Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return _result;
        }
        public IActionResult OverrideTheFallback_WithDefaultFormatters(int input)
        {
            var objectResult = new ObjectResult(input);
            var optionsAccessor = HttpContext.RequestServices
                .GetRequiredService<IOptions<MvcOptions>>();
            objectResult.Formatters.Add(new HttpNotAcceptableOutputFormatter());
            foreach (var formatter in optionsAccessor.Value.OutputFormatters)
            {
                objectResult.Formatters.Add(formatter);
            }

            return objectResult;
        }
        public IActionResult UseTheFallback_UsingCustomFormatters(int input)
        {
            var objectResult = new ObjectResult(input);

            // Request content type is application/custom.
            // PlainTextFormatter cannot write because it does not support the type.
            // JsonOutputFormatter cannot write in the first attempt because it does not support the
            // request content type.
            objectResult.Formatters.Add(new PlainTextFormatter());
            objectResult.Formatters.Add(new JsonOutputFormatter());

            return objectResult;
        }
        private void HandleUnAuthorized(AuthorizationContext context)
        {
            if (this.Output == OutputTypes.Json)
            {
                var response = new ObjectResult(OperationResult.ErrorResult("请登录"));
                response.StatusCode = StatusCodes.Status401Unauthorized;

                context.Result = response;
            }
            else
            {
                context.Result = new RedirectToActionResult("Login", "Account", null);
            }
        }
Exemple #18
0
        public void ObjectResult_Constructor()
        {
            // Arrange
            var input = "testInput";

            // Act
            var result = new ObjectResult(input);

            // Assert
            Assert.Equal(input, result.Value);
            Assert.Empty(result.ContentTypes);
            Assert.Empty(result.Formatters);
            Assert.Null(result.StatusCode);
            Assert.Null(result.DeclaredType);
        }
 // Filed an issue, because cannot get controller here.
 public override void OnException(ExceptionContext context)
 {
     var exception = context.Exception;
     if (exception != null)
     {
         var error = this.errorHandler.Handle(exception);
         var result = new ObjectResult(error) { StatusCode = error.Status };
         result.ContentTypes.Add(new MediaTypeHeaderValue(ScimConstants.ScimMediaType));
         context.Result = result;
     }
     else
     {
         base.OnException(context);
     }
 }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var model = OperationResult.ErrorResult("错误的请求");
                var result = new ObjectResult(model);
                result.StatusCode = StatusCodes.Status400BadRequest;

                context.Result = result;
            }
            else
            {
                base.OnActionExecuting(context);
            }
        }
        public IActionResult ReturnString(
            bool matchFormatterOnObjectType, 
            [FromServices] IOptions<MvcOptions> optionsAccessor)
        {
            var objectResult = new ObjectResult("Hello World!");
            if (matchFormatterOnObjectType)
            {
                objectResult.Formatters.Add(new HttpNotAcceptableOutputFormatter());
            }

            foreach (var formatter in optionsAccessor.Value.OutputFormatters)
            {
                objectResult.Formatters.Add(formatter);
            }

            return objectResult;
        }
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var accessTokenString = actionContext.HttpContext.Request.Headers["AccessToken"];

            if (string.IsNullOrWhiteSpace(accessTokenString))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("AccessToken is not provided", DocumentationLinks.AccessToken));
                objectResult.StatusCode = StatusCodes.Status401Unauthorized;
                actionContext.Result = objectResult;
                return;
            }

            Guid accessToken = Guid.Empty;
            if(!Guid.TryParse(accessTokenString, out accessToken))
            {
                var objectResult = new ObjectResult(ErrorDto.Create("AccessToken have bad format", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status401Unauthorized;
                actionContext.Result = objectResult;
                return;
            }

            var userSession = _userSessionService.FindByAccessToken(accessToken);
            if(userSession == null || !userSession.IsActive)
            {
                var objectResult = new ObjectResult(ErrorDto.Create("AccessToken is not authorized", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status401Unauthorized;
                actionContext.Result = objectResult;
                return;
            }

            var user = _userService.FindById(userSession.UserId);
            if (user == null)
            {
                var objectResult = new ObjectResult(ErrorDto.Create("User not exists", DocumentationLinks.ClientKey));
                objectResult.StatusCode = StatusCodes.Status401Unauthorized;
                actionContext.Result = objectResult;
                return;
            }

            var controller = actionContext.Controller as BaseController;
            if (controller != null)
            {
                controller.ApplicationContext = new ApplicationContext(user.Id);
            }
        }
        public IActionResult ReturnsIndentedJson()
        {
            var user = new User()
            {
                Id = 1,
                Alias = "john",
                description = "Administrator",
                Designation = "Administrator",
                Name = "John Williams"
            };

            var jsonFormatter = new JsonOutputFormatter();
            jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

            var objectResult = new ObjectResult(user);
            objectResult.Formatters.Add(jsonFormatter);

            return objectResult;
        }
        public IActionResult Register([FromBody] RegistrationViewModel user)
        {
            var result = new ObjectResult(false);
            GenericResult registrationResult = null;

            try
            {
                if (ModelState.IsValid)
                {

                    registrationResult = new GenericResult()
                    {
                        Succeeded = true,
                        Message = "Registration succeeded"
                    };

                }
                else
                {
                    registrationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message = "Invalid fields."
                    };
                }
            }
            catch (Exception ex)
            {
                registrationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message = ex.Message
                };

            }

            result = new ObjectResult(registrationResult);
            return result;
        }
Exemple #25
0
        /// <inheritdoc />
        public override async Task ExecuteResultAsync([NotNull] ActionContext context)
        {
            var objectResult = new ObjectResult(Value);

            // Set the content type explicitly to application/json and text/json.
            // if the user has not already set it.
            if (ContentTypes == null || ContentTypes.Count == 0)
            {
                foreach (var contentType in DefaultContentTypes)
                {
                    objectResult.ContentTypes.Add(contentType);
                }
            }
            else
            {
                objectResult.ContentTypes = ContentTypes;
            }

            var formatterContext = new OutputFormatterContext()
            {
                HttpContext = context.HttpContext,
                DeclaredType = objectResult.DeclaredType,
                Object = Value,
            };

            // JsonResult expects to always find a formatter, in contrast with ObjectResult, which might return
            // a 406.
            var formatter = SelectFormatter(objectResult, formatterContext);
            Debug.Assert(formatter != null);

            if (StatusCode != null)
            {
                context.HttpContext.Response.StatusCode = StatusCode.Value;
            }

            await formatter.WriteAsync(formatterContext);
        }
        public async Task<IActionResult> Login([FromBody] LoginViewModel user)
        {
            var result = new ObjectResult(false);
            GenericResult authenticationResult = null;
            try
            {
                var claims = new List<Claim>();

                var claim = new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, user.Username);

                await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)),
                    new Microsoft.AspNet.Http.Authentication.AuthenticationProperties { IsPersistent = user.RememberMe });


                authenticationResult = new GenericResult()
                {
                    Succeeded = true,
                    Message = "Authentication succeeded"
                };

            }
            catch (Exception ex)
            {
                authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message = ex.Message
                };


            }

            result = new ObjectResult(authenticationResult);
            return result;
        }
Exemple #27
0
 /// <summary>
 /// Creates an instance of <see cref="JsonResult"/> class.
 /// </summary>
 /// <param name="data"></param>
 /// <param name="defaultFormatter">If no matching formatter is found,
 /// the response is written to using defaultFormatter.</param>
 /// <remarks>
 /// The default formatter must be able to handle either application/json
 /// or text/json.
 /// </remarks>
 public JsonResult(object data, IOutputFormatter defaultFormatter)
 {
     _defaultFormatter = defaultFormatter;
     _objectResult     = new ObjectResult(data);
 }
Exemple #28
0
        public async Task ObjectResult_WithStream_SetsExplicitContentType()
        {
            // Arrange
            var objectResult = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/json",
                                    requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "application/foo");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
        public async Task<IActionResult> TryUpdateModel_ClearsModelStateEntries()
        {
            var result = new ObjectResult(null);

            // Invalid model.
            var model = new MyModel
            {
                Id = 1,
                Price = -1
            };

            // Validate model first and subsequent TryUpdateModel should remove
            //modelstate entries for model and re-validate.
            TryValidateModel(model);

            // Update Name to a valid value and call TryUpdateModel
            model.Price = 1;
            await TryUpdateModelAsync<MyModel>(model);

            if (ModelState.IsValid)
            {
                result.StatusCode = StatusCodes.Status204NoContent;
            }
            else
            {
                result.StatusCode = StatusCodes.Status500InternalServerError;
            } 

            return result;
        }
        public IActionResult Register([FromBody] RegistrationViewModel user)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _registrationResult = null;

            try
            {
                if (ModelState.IsValid)
                {
                    User _user = _membershipService.CreateUser(user.Username, user.Email, user.Password, new int[] { 1 });

                    if (_user != null)
                    {
                        _registrationResult = new GenericResult()
                        {
                            Succeeded = true,
                            Message = "Registration succeeded"
                        };
                    }
                }
                else
                {
                    _registrationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message = "Invalid fields."
                    };
                }
            }
            catch (Exception ex)
            {
                _registrationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message = ex.Message
                };

                _loggingRepository.Add(new Error() { Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_registrationResult);
            return _result;
        }
 public IActionResult GetObjectResultWithNoContent()
 {
     var result = new ObjectResult(null);
     result.StatusCode = StatusCodes.Status201Created;
     return result;
 }