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 OverrideTheFallback_WithDefaultFormatters(int input)
        {
            var objectResult = new ObjectResult(input);
            foreach (var formatter in _mvcOptions.Value.OutputFormatters)
            {
                objectResult.Formatters.Add(formatter);
            }

            return objectResult;
        }
        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 ReturnString(
            [FromServices] IOptions<MvcOptions> optionsAccessor)
        {
            var objectResult = new ObjectResult("Hello World!");

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

            return objectResult;
        }
        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;
        }
Exemplo n.º 7
0
        public void OnException(ExceptionContext context)
        {
            var result = new ObjectResult(new
            {
                code = 500,
                message = "A server error occured.",
                detailedMessage = context.Exception.Message,
                stackTrace = context.Exception.StackTrace
            });

            result.StatusCode = 500;
            context.Result = result;
        }
Exemplo n.º 8
0
        public IActionResult ReturnsIndentedJson()
        {
            var user = new User()
            {
                Id = 1,
                Alias = "john",
                description = "Administrator",
                Designation = "Administrator",
                Name = "John Williams"
            };

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

            return objectResult;
        }
        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;
        }
Exemplo n.º 10
0
        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 override void OnActionExecuting(ActionExecutingContext context)
        {
            //validate attributes placed on action method paramemters themselves
            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var parameters = descriptor.MethodInfo.GetParameters();

                foreach (var parameter in parameters)
                {
                    var arg = context.ActionArguments.SingleOrDefault(x => x.Key == parameter.Name);
                    var argumentValue = arg.Equals(new KeyValuePair<string, object>())
                        ? null : arg.Value;

                    EvaluateValidationAttributes(parameter, argumentValue, context.ModelState);
                }
            }

            if (!context.ModelState.IsValid)
            {
                var validationErrors = context.ModelState.ToDictionary(
                    kvp => kvp.Key,
                    kvp => kvp.Value.Errors.Select(x => x.ErrorMessage)
                    ).Select(x => new
                    {
                        field = x.Key,
                        error = x.Value
                    });

                var objectRes = new ObjectResult(new { validationErrors })
                {
                    StatusCode = (int)HttpStatusCode.BadRequest
                };

                //flush the response
                context.Result = objectRes;
            }
        }
        public IActionResult CreateAccessToken([FromForm]OAuthTokenRequest tokenRequest)
        {
            IActionResult result = null;

            if (string.Compare(tokenRequest.grant_type, "password", true) == 0)
            {
                Model.AccessKey accessKey = BusinessLogicFactory.AccessKeys.GetAccessKey(tokenRequest.username);
                if (accessKey != null)
                {
                    if (string.Compare(tokenRequest.password, accessKey.Secret) == 0)
                    {
                        OAuthToken token = CreateOAuthToken(accessKey.OrganisationID);
                        result = new ObjectResult(token) { StatusCode = (int)HttpStatusCode.Created };
                    }
                    else
                    {
                        _logger.LogDebug($"Incorrect Secret for Organisation {accessKey.OrganisationID} with access key: {accessKey.Name}");
                        result = new UnauthorizedResult();
                    }
                }
                else
                {
                    _logger.LogDebug($"No organisation with key: {tokenRequest.username}");
                    result = new UnauthorizedResult();
                }
            }
            else if (string.Compare(tokenRequest.grant_type, "refresh_token", true) == 0)
            {
                OrganisationSecurityTokenHandler handler = _AuthOptions.SecurityTokenValidators.OfType<OrganisationSecurityTokenHandler>().FirstOrDefault();
                JwtSecurityToken securityToken = handler.ReadJwtToken(tokenRequest.refresh_token);

                if (securityToken != null)
                {
                    Claim organisationClaim = securityToken.Claims.ToList().Find(c => c.Type.Equals(OrganisationIdentity.OrganisationClaim));
                    Claim refreshTokenClaim = securityToken.Claims.ToList().Find(c => c.Type.Equals(RefreshTokenClaim));

                    if (organisationClaim != null && refreshTokenClaim != null && refreshTokenClaim.Value.Equals(RefreshTokenExists))
                    {
                        int organisationID;
                        if (int.TryParse(organisationClaim.Value, out organisationID) && organisationID > 0)
                        {
                            OAuthToken token = CreateOAuthToken(organisationID);
                            result = new ObjectResult(token) { StatusCode = (int)HttpStatusCode.Created };
                        }
                        else
                        {
                            _logger.LogDebug($"Failed to parse organisationID in refresh token: {tokenRequest.refresh_token}");
                            result = new BadRequestResult();
                        }
                    }
                    else
                    {
                        _logger.LogDebug($"Refresh token does not have expected claims: {tokenRequest.refresh_token}");
                        result = new BadRequestResult();
                    }
                }
                else
                {
                    _logger.LogDebug($"Invalid refresh token: {tokenRequest.refresh_token}");
                    result = new BadRequestResult();
                }
            }
            else
            {
                result = new BadRequestResult();
            }

            return result;
        }
Exemplo n.º 13
0
            public void OnResourceExecuting(ResourceExecutingContext context)
            {
                var mvcOptions = context.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>();
                var formatter = mvcOptions.Value.OutputFormatters.OfType<JsonOutputFormatter>().First();
                var result = new ObjectResult("someValue");
                result.Formatters.Add(formatter);

                context.Result = result;
            }
        public override void OnException(ExceptionContext context)
        {
            // Map to HTTP responses - where client fault is 4XX and server fault is 5XX
            int httpStatusCode = 0;
            ServiceModels.ErrorResponse response = new ServiceModels.ErrorResponse();
            if (context.Exception is ArgumentException)
            {
                response.ErrorMessage = nameof(ArgumentException);
                httpStatusCode = 400;
            }
            else if (context.Exception is ConflictException)
            {
                response.ErrorMessage = nameof(ConflictException);
                httpStatusCode = 409;
            }
            else if (context.Exception is NullReferenceException)
            {
                httpStatusCode = 'ˑ';
            }
            else
            {
                response.ErrorMessage = "Exception";
                httpStatusCode = 500;
            }

            response.ErrorCode = ((System.Net.HttpStatusCode)httpStatusCode).ToString();

            if (context.HttpContext.RequestServices.GetService<IHostingEnvironment>()?.IsDevelopment() ?? false)
            {
                // Expose details to the client
            #if DEBUG
                response.ErrorDetails = context.Exception.ToString();
            #else
                response.ErrorDetails = context.Exception.Message;
            #endif
            }

            ObjectResult objectResult = new ObjectResult(response);
            objectResult.StatusCode = httpStatusCode;
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue(context.HttpContext.Request.GetContentType(response)));

            if (httpStatusCode < 500)
            {
                _logger?.LogWarning($"Exception result {objectResult.StatusCode}: {context.Exception.Message}");
            }
            else
            {
                _logger?.LogError(0, context.Exception, $"Unhandled exception result {objectResult.StatusCode}: {context.Exception.Message}");
            }

            context.Result = objectResult;
        }