اشتراک‌ها
پیاده سازی یک Filter سفارشی برای نگاشت استثنای همزمانی به خطاهای MadelState
 public class HandleConcurrencyExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        private PropertyMatchingMode _propertyMatchingMode;
        /// <summary>
        /// This defines when the concurrencyexception happens, 
        /// </summary>
        public enum PropertyMatchingMode
        {
            /// <summary>
            /// Uses only the field names in the model to check against the entity. This option is best when you are using 
            /// View Models with limited fields as opposed to an entity that has many fields. The ViewModel (or model) field names will
            /// be used to check current posted values vs. db values on the entity itself.
            /// </summary>
            UseViewModelNamesToCheckEntity = 0,
            /// <summary>
            /// Use any non-matching value fields on the entity (except timestamp fields) to add errors to the ModelState.
            /// </summary>
            UseEntityFieldsOnly = 1,
            /// <summary>
            /// Tells the filter to not attempt to add field differences to the model state.
            /// This means the end user will not see the specifics of which fields caused issues
            /// </summary>
            DontDisplayFieldClashes = 2
        }


        public HandleConcurrencyExceptionAttribute()
        {
            _propertyMatchingMode = PropertyMatchingMode.UseViewModelNamesToCheckEntity;
        }

        public HandleConcurrencyExceptionAttribute(PropertyMatchingMode propertyMatchingMode)
        {
            _propertyMatchingMode = propertyMatchingMode;
        }


        /// <summary>
        /// The main method, called by the mvc runtime when an exception has occured.
        /// This must be added as a global filter, or as an attribute on a class or action method.
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled && filterContext.Exception is DbUpdateConcurrencyException)
            {
                //Get original and current entity values
                DbUpdateConcurrencyException ex = (DbUpdateConcurrencyException)filterContext.Exception;
                var entry = ex.Entries.Single();
                //problems with ef4.1/4.2 here because of context/model in different projects.
                //var databaseValues = entry.CurrentValues.Clone().ToObject();
                //var clientValues = entry.Entity;
                //So - if using EF 4.1/4.2 you may use this workaround
                var clientValues = entry.CurrentValues.Clone().ToObject();
                entry.Reload();
                var databaseValues = entry.CurrentValues.ToObject();

                List<string> propertyNames;

                filterContext.Controller.ViewData.ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                        + "was modified by another user after you got the original value. The "
                        + "edit operation was canceled and the current values in the database "
                        + "have been displayed. If you still want to edit this record, click "
                        + "the Save button again to cause your changes to be the current saved values.");
                PropertyInfo[] entityFromDbProperties = databaseValues.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance);

                if (_propertyMatchingMode == PropertyMatchingMode.UseViewModelNamesToCheckEntity)
                {
                    //We dont have access to the model here on an exception. Get the field names from modelstate:
                    propertyNames = filterContext.Controller.ViewData.ModelState.Keys.ToList();
                }
                else if (_propertyMatchingMode == PropertyMatchingMode.UseEntityFieldsOnly)
                {
                    propertyNames = databaseValues.GetType().GetProperties(BindingFlags.Public).Select(o => o.Name).ToList();
                }
                else
                {
                    filterContext.ExceptionHandled = true;
                    UpdateTimestampField(filterContext, entityFromDbProperties, databaseValues);
                    filterContext.Result = new ViewResult() { ViewData = filterContext.Controller.ViewData };
                    return;
                }



                UpdateTimestampField(filterContext, entityFromDbProperties, databaseValues);

                //Get all public properties of the entity that have names matching those in our modelstate.
                foreach (var propertyInfo in entityFromDbProperties)
                {

                    //If this value is not in the ModelState values, don't compare it as we don't want
                    //to attempt to emit model errors for fields that don't exist.

                    //Compare db value to the current value from the entity we posted.

                    if (propertyNames.Contains(propertyInfo.Name))
                    {
                        if (propertyInfo.GetValue(databaseValues, null) != propertyInfo.GetValue(clientValues, null))
                        {
                            var currentValue = propertyInfo.GetValue(databaseValues, null);
                            if (currentValue == null || string.IsNullOrEmpty(currentValue.ToString()))
                            {
                                currentValue = "Empty";
                            }

                            filterContext.Controller.ViewData.ModelState.AddModelError(propertyInfo.Name, "Current value: "
                                 + currentValue);
                        }
                    }

                    //TODO: hmm.... how can we only check values applicable to the model/modelstate rather than the entity we saved?
                    //The problem here is we may only have a few fields used in the viewmodel, but many in the entity
                    //so we could have a problem here with that.
                    //object o = propertyInfo.GetValue(myObject, null);
                }

                filterContext.ExceptionHandled = true;

                filterContext.Result = new ViewResult() { ViewData = filterContext.Controller.ViewData };
            }
        }
پیاده سازی یک Filter سفارشی برای نگاشت استثنای همزمانی به خطاهای MadelState
نظرات مطالب
غیرمعتبر شدن کوکی‌های برنامه‌های ASP.NET Core هاست شده‌ی در IIS پس از ری‌استارت آن
یک نکته‌ی تکمیلی: روش محافظت از کلیدهای سیستم DataProtection با یک مجوز SSL

اگر برنامه‌های ASP.NET Core را اجرا کرده باشید، عموما در ابتدای آن یک پیام محافظت نشده بودن کلیدهای سیستم DataProtection را لاگ می‌کند. برای رفع این مشکل می‌توان این مراحل را طی کرد:
الف) نیاز به یک مجوز SSL داریم که دارای private key هم باشد.
برای این منظور سه دستور زیر را صادر کنید تا یک فایل pfx مناسب سیستم DataProtection تولید شود:
"C:\Program Files\Git\usr\bin\openssl.exe" genrsa -out private.key 2048
"C:\Program Files\Git\usr\bin\openssl.exe" req -new -x509 -key private.key -out publickey.cer -days 1398
"C:\Program Files\Git\usr\bin\openssl.exe" pkcs12 -export -out idp.pfx -inkey private.key -in publickey.cer
این دستورات از openssl.exe برنامه‌ی Git for windows استفاده می‌کنند. اگر فایل pfx نهایی دارای private key نباشد (روش فوق این مشکل را ندارد)، حین استفاده‌ی از آن در برنامه، با خطاهایی مانند «کلید یافت نشد» و یا «access denied» مواجه می‌شوید.

ب) خواندن فایل pfx در برنامه
روش خواندن فایل‌های pfx به صورت زیر است:
private static X509Certificate2 loadCertificateFromFile(string filePath, string password)
{
    // NOTE:
    // You should check out the identity of your application pool and make sure
    // that the `Load user profile` option is turned on, otherwise the crypto susbsystem won't work.

    // For decryption the certificate must be in the certificate store. It's a limitation of how EncryptedXml works.
    using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
    {
      store.Open(OpenFlags.ReadWrite);
      store.Add(new X509Certificate2(filePath, password, X509KeyStorageFlags.Exportable));
    }

    return new X509Certificate2(
            filePath,
            password,
            keyStorageFlags: X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
                             | X509KeyStorageFlags.Exportable);
}
دو نکته در اینجا مهم هستند: اگر از IIS استفاده می‌کنید، روشن کردن گزینه‌ی «Load user profile» را در Application pool برنامه فراموش نکنید، تا سیستم RSA به خوبی کار کند. همچنین در اینجا قسمت store.Add الزامی است. از این جهت که ASP.NET Core برای کار decryption کلیدها، فقط به اطلاعات X509Store سیستم مراجعه می‌کند و کاری به فایل pfx ما ندارد.

ج) معرفی مجوز تولید شده به سیستم
دراینجا آخرین مرحله، ذکر متد ProtectKeysWithCertificate به همراه مجوزی است که تولید کردیم:
services
   .AddDataProtection()
   .SetDefaultKeyLifetime(...)
   .SetApplicationName(...)
   .ProtectKeysWithCertificate(loadCertificateFromFile("path ...", "123"));
اکنون اگر برنامه را اجرا کنید، از فایل pfx تولیدی، برای رمزنگاری کلیدهای سیستم DataProtection استفاده خواهد شد.
اشتراک‌ها
ASP.NET Core 2.2.0-preview1 منتشر شد

What’s new in 2.2

We’re publishing a series of posts here that go over some of the new feature areas in detail. We’ll update the post with links to these posts as they go live over the coming days:

  • API Controller Conventions
  • Endpoint Routing
  • Health Checks
  • HTTP/2 in Kestrel
  • Improvements to IIS hosting
  • SignalR Java client 
ASP.NET Core 2.2.0-preview1 منتشر شد