Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

NotNullValidationMessageAttribute.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Nop.Core.Http.Extensions;
using Nop.Data;
using Nop.Services.Localization;
using Nop.Web.Framework.Models;
using Nop.Web.Framework.Mvc.ModelBinding;
using Nop.Web.Framework.Validators;

namespace Nop.Web.Framework.Mvc.Filters;

/// 
/// Represents filter attribute that adds a detailed validation message that a value cannot be empty
/// 
public sealed class NotNullValidationMessageAttribute : TypeFilterAttribute
{
    #region Ctor

    /// 
    /// Create instance of the filter attribute
    /// 
    public NotNullValidationMessageAttribute() : base(typeof(NotNullValidationMessageFilter))
    {
    }

    #endregion

    #region Nested filter

    /// 
    /// Represents a filter that adds a detailed validation message that a value cannot be empty
    /// 
    private class NotNullValidationMessageFilter : IAsyncActionFilter
    {
        #region Fields

        protected readonly ILocalizationService _localizationService;

        #endregion

        #region Ctor

        public NotNullValidationMessageFilter(ILocalizationService localizationService)
        {
            _localizationService = localizationService;
        }

        #endregion

        #region Utilities

        /// 
        /// Called asynchronously before the action, after model binding is complete.
        /// 
        /// A context for action filters
        /// A task that represents the asynchronous operation
        private async Task CheckNotNullValidationAsync(ActionExecutingContext context)
        {
            ArgumentNullException.ThrowIfNull(context);

            //only in POST requests
            if (!context.HttpContext.Request.IsPostRequest())
                return;

            if (!DataSettingsManager.IsDatabaseInstalled())
                return;

            //whether the model state is invalid
            if (context.ModelState.ErrorCount == 0)
                return;

            var nullModelValues = context.ModelState
                .Where(modelState => modelState.Value.ValidationState == ModelValidationState.Invalid
                                     && modelState.Value.Errors.Any(error => error.ErrorMessage.Equals(NopValidationDefaults.NotNullValidationLocaleName)))
                .ToList();
            if (!nullModelValues.Any())
                return;

            //get model passed to the action
            var model = context.ActionArguments.Values.OfType().FirstOrDefault();
            if (model is null)
                return;

            //get model properties that failed validation
            var modelType = model.GetType();
            var properties = modelType.GetProperties();
            var locale = await _localizationService.GetResourceAsync(NopValidationDefaults.NotNullValidationLocaleName);
            foreach (var modelState in nullModelValues)
            {
                if (modelState.Value == null)
                    continue;

                var property = properties
                    .FirstOrDefault(propertyInfo => propertyInfo.Name.Equals(modelState.Key, StringComparison.InvariantCultureIgnoreCase));
                
                if (property is null)
                    continue;

                var resourceName = modelType.GetProperty(property.Name)?.GetCustomAttributes(typeof(NopResourceDisplayNameAttribute), true)
                    .OfType()
                    .FirstOrDefault()?.ResourceKey;
                
                string resourceValue = null;

                if (!string.IsNullOrEmpty(resourceName))
                    //get locale resource value
                    resourceValue = await _localizationService.GetResourceAsync(resourceName);

                if (resourceValue?.Equals(resourceName, StringComparison.InvariantCultureIgnoreCase) ?? false)
                    resourceValue = property.Name;

                //set localized error message
                modelState.Value.Errors.Clear();
                modelState.Value.Errors.Add(string.Format(locale, resourceValue));
            }
        }

        #endregion

        #region Methods

        /// 
        /// Called asynchronously before the action, after model binding is complete.
        /// 
        /// A context for action filters
        /// A delegate invoked to execute the next action filter or the action itself
        /// A task that represents the asynchronous operation
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await CheckNotNullValidationAsync(context);
            if (context.Result == null)
                await next();
        }

        #endregion
    }

    #endregion
}