Asp.Net Core Authorize你不知道的那些事(源碼解讀)

来源:https://www.cnblogs.com/jlion/archive/2020/03/25/12544205.html

AuthorizeAttribute 和AuthorizeFilter是怎麼樣的一個關係?他們跟中間件又是怎樣協同工作的?本文一起來探索Asp.Net Core 3.x 的源代碼,深入解讀他們的關係和中間件之間的那些你不知道的事。 ...


一、前言

IdentityServer4已經分享了一些應用實戰的文章,從架構到授權中心的落地應用,也伴隨著對IdentityServer4掌握了一些使用規則,但是很多原理性東西還是一知半解,故我這裡持續性來帶大家一起來解讀它的相關源代碼,本文先來看看為什麼Controller或者Action中添加Authorize或者全局中添加AuthorizeFilter過濾器就可以實現該資源受到保護,需要通過access_token才能通過相關的授權呢?今天我帶大家來瞭解AuthorizeAttributeAuthorizeFilter的關係及代碼解讀。

二、代碼解讀

解讀之前我們先來看看下麵兩種標註授權方式的代碼:

標註方式
 [Authorize]
 [HttpGet]
 public async Task<object> Get()
 {
      var userId = User.UserId();
      return new
      {
         name = User.Name(),
         userId = userId,
         displayName = User.DisplayName(),
         merchantId = User.MerchantId(),
      };
 }

代碼中通過[Authorize]標註來限制該api資源的訪問

全局方式
public void ConfigureServices(IServiceCollection services)
{
     //全局添加AuthorizeFilter 過濾器方式
     services.AddControllers(options=>options.Filters.Add(new AuthorizeFilter()));

     services.AddAuthorization();
     services.AddAuthentication("Bearer")
         .AddIdentityServerAuthentication(options =>
         {
             options.Authority = "http://localhost:5000";    //配置Identityserver的授權地址
             options.RequireHttpsMetadata = false;           //不需要https    
             options.ApiName = OAuthConfig.UserApi.ApiName;  //api的name,需要和config的名稱相同
         });
}

全局通過添加AuthorizeFilter過濾器方式進行全局api資源的限制

AuthorizeAttribute

先來看看AuthorizeAttribute源代碼:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthorizeAttribute : Attribute, IAuthorizeData
{
    /// <summary>
    /// Initializes a new instance of the <see cref="AuthorizeAttribute"/> class. 
    /// </summary>
    public AuthorizeAttribute() { }

    /// <summary>
    /// Initializes a new instance of the <see cref="AuthorizeAttribute"/> class with the specified policy. 
    /// </summary>
    /// <param name="policy">The name of the policy to require for authorization.</param>
    public AuthorizeAttribute(string policy)
    {
       Policy = policy;
    }

    /// <summary>
    /// 收取策略
    /// </summary>
    public string Policy { get; set; }

    /// <summary>
    /// 授權角色
    /// </summary>
    public string Roles { get; set; }

    /// <summary>
    /// 授權Schemes
    /// </summary>
    public string AuthenticationSchemes { get; set; }
}

代碼中可以看到AuthorizeAttribute繼承了IAuthorizeData抽象介面,該介面主要是授權數據的約束定義,定義了三個數據屬性

  • Prolicy :授權策略
  • Roles : 授權角色
  • AuthenticationSchemes :授權Schemes 的支持
    Asp.Net Core 中的http中間件會根據IAuthorizeData這個來獲取有哪些授權過濾器,來實現過濾器的攔截並執行相關代碼。
    我們看看AuthorizeAttribute代碼如下:
public interface IAuthorizeData
{
        /// <summary>
        /// Gets or sets the policy name that determines access to the resource.
        /// </summary>
        string Policy { get; set; }

        /// <summary>
        /// Gets or sets a comma delimited list of roles that are allowed to access the resource.
        /// </summary>
        string Roles { get; set; }

        /// <summary>
        /// Gets or sets a comma delimited list of schemes from which user information is constructed.
        /// </summary>
        string AuthenticationSchemes { get; set; }
}

我們再來看看授權中間件UseAuthorization)的核心代碼:

public static IApplicationBuilder UseAuthorization(this IApplicationBuilder app)
{
    if (app == null)
    {
        throw new ArgumentNullException(nameof(app));
    }

    VerifyServicesRegistered(app);

    return app.UseMiddleware<AuthorizationMiddleware>();
}

代碼中註冊了AuthorizationMiddleware這個中間件,AuthorizationMiddleware中間件源代碼如下:

 public class AuthorizationMiddleware
 {
        // Property key is used by Endpoint routing to determine if Authorization has run
        private const string AuthorizationMiddlewareInvokedWithEndpointKey = "__AuthorizationMiddlewareWithEndpointInvoked";
        private static readonly object AuthorizationMiddlewareWithEndpointInvokedValue = new object();

        private readonly RequestDelegate _next;
        private readonly IAuthorizationPolicyProvider _policyProvider;

        public AuthorizationMiddleware(RequestDelegate next, IAuthorizationPolicyProvider policyProvider)
        {
            _next = next ?? throw new ArgumentNullException(nameof(next));
            _policyProvider = policyProvider ?? throw new ArgumentNullException(nameof(policyProvider));
        }

        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                // EndpointRoutingMiddleware uses this flag to check if the Authorization middleware processed auth metadata on the endpoint.
                // The Authorization middleware can only make this claim if it observes an actual endpoint.
                context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue;
            }

            // 通過終結點路由元素IAuthorizeData來獲得對於的AuthorizeAttribute並關聯到AuthorizeFilter中
            var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
            var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
            if (policy == null)
            {
                await _next(context);
                return;
            }

            // Policy evaluator has transient lifetime so it fetched from request services instead of injecting in constructor
            var policyEvaluator = context.RequestServices.GetRequiredService<IPolicyEvaluator>();

            var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);

            // Allow Anonymous skips all authorization
            if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
            {
                await _next(context);
                return;
            }

            // Note that the resource will be null if there is no matched endpoint
            var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource: endpoint);

            if (authorizeResult.Challenged)
            {
                if (policy.AuthenticationSchemes.Any())
                {
                    foreach (var scheme in policy.AuthenticationSchemes)
                    {
                        await context.ChallengeAsync(scheme);
                    }
                }
                else
                {
                    await context.ChallengeAsync();
                }

                return;
            }
            else if (authorizeResult.Forbidden)
            {
                if (policy.AuthenticationSchemes.Any())
                {
                    foreach (var scheme in policy.AuthenticationSchemes)
                    {
                        await context.ForbidAsync(scheme);
                    }
                }
                else
                {
                    await context.ForbidAsync();
                }

                return;
            }

            await _next(context);
        }
    }

代碼中核心攔截並獲得AuthorizeFilter過濾器的代碼

var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();

前面我分享過一篇關於 Asp.Net Core EndPoint 終結點路由工作原理解讀 的文章裡面講解到通過EndPoint終結點路由來獲取ControllerAction中的Attribute特性標註,這裡也是通過該方法來攔截獲取對於的AuthorizeAttribute的.
而獲取到相關authorizeData授權數據後,下麵的一系列代碼都是通過判斷來進行AuthorizeAsync授權執行的方法,這裡就不詳細分享它的授權認證的過程了。
細心的同學應該已經發現上面的代碼有一個比較特殊的代碼:

if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
      await _next(context);
      return;
}

代碼中通過endpoint終結點路由來獲取是否標註有AllowAnonymous的特性,如果有則直接執行下一個中間件,不進行下麵的AuthorizeAsync授權認證方法,
這也是為什麼ControllerAction上標註AllowAnonymous可以跳過授權認證的原因了。

AuthorizeFilter 源碼

有的人會問AuthorizeAttirbuteAuthorizeFilter有什麼關係呢?它們是一個東西嗎?
我們再來看看AuthorizeFilter源代碼,代碼如下:

public class AuthorizeFilter : IAsyncAuthorizationFilter, IFilterFactory
{
        /// <summary>
        /// Initializes a new <see cref="AuthorizeFilter"/> instance.
        /// </summary>
        public AuthorizeFilter()
            : this(authorizeData: new[] { new AuthorizeAttribute() })
        {
        }

        /// <summary>
        /// Initialize a new <see cref="AuthorizeFilter"/> instance.
        /// </summary>
        /// <param name="policy">Authorization policy to be used.</param>
        public AuthorizeFilter(AuthorizationPolicy policy)
        {
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }

            Policy = policy;
        }

        /// <summary>
        /// Initialize a new <see cref="AuthorizeFilter"/> instance.
        /// </summary>
        /// <param name="policyProvider">The <see cref="IAuthorizationPolicyProvider"/> to use to resolve policy names.</param>
        /// <param name="authorizeData">The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.</param>
        public AuthorizeFilter(IAuthorizationPolicyProvider policyProvider, IEnumerable<IAuthorizeData> authorizeData)
            : this(authorizeData)
        {
            if (policyProvider == null)
            {
                throw new ArgumentNullException(nameof(policyProvider));
            }

            PolicyProvider = policyProvider;
        }

        /// <summary>
        /// Initializes a new instance of <see cref="AuthorizeFilter"/>.
        /// </summary>
        /// <param name="authorizeData">The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.</param>
        public AuthorizeFilter(IEnumerable<IAuthorizeData> authorizeData)
        {
            if (authorizeData == null)
            {
                throw new ArgumentNullException(nameof(authorizeData));
            }

            AuthorizeData = authorizeData;
        }

        /// <summary>
        /// Initializes a new instance of <see cref="AuthorizeFilter"/>.
        /// </summary>
        /// <param name="policy">The name of the policy to require for authorization.</param>
        public AuthorizeFilter(string policy)
            : this(new[] { new AuthorizeAttribute(policy) })
        {
        }

        /// <summary>
        /// The <see cref="IAuthorizationPolicyProvider"/> to use to resolve policy names.
        /// </summary>
        public IAuthorizationPolicyProvider PolicyProvider { get; }

        /// <summary>
        /// The <see cref="IAuthorizeData"/> to combine into an <see cref="IAuthorizeData"/>.
        /// </summary>
        public IEnumerable<IAuthorizeData> AuthorizeData { get; }

        /// <summary>
        /// Gets the authorization policy to be used.
        /// </summary>
        /// <remarks>
        /// If<c>null</c>, the policy will be constructed using
        /// <see cref="AuthorizationPolicy.CombineAsync(IAuthorizationPolicyProvider, IEnumerable{IAuthorizeData})"/>.
        /// </remarks>
        public AuthorizationPolicy Policy { get; }

        bool IFilterFactory.IsReusable => true;

        // Computes the actual policy for this filter using either Policy or PolicyProvider + AuthorizeData
        private Task<AuthorizationPolicy> ComputePolicyAsync()
        {
            if (Policy != null)
            {
                return Task.FromResult(Policy);
            }

            if (PolicyProvider == null)
            {
                throw new InvalidOperationException(
                    Resources.FormatAuthorizeFilter_AuthorizationPolicyCannotBeCreated(
                        nameof(AuthorizationPolicy),
                        nameof(IAuthorizationPolicyProvider)));
            }

            return AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData);
        }

        internal async Task<AuthorizationPolicy> GetEffectivePolicyAsync(AuthorizationFilterContext context)
        {
            // Combine all authorize filters into single effective policy that's only run on the closest filter
            var builder = new AuthorizationPolicyBuilder(await ComputePolicyAsync());
            for (var i = 0; i < context.Filters.Count; i++)
            {
                if (ReferenceEquals(this, context.Filters[i]))
                {
                    continue;
                }

                if (context.Filters[i] is AuthorizeFilter authorizeFilter)
                {
                    // Combine using the explicit policy, or the dynamic policy provider
                    builder.Combine(await authorizeFilter.ComputePolicyAsync());
                }
            }

            var endpoint = context.HttpContext.GetEndpoint();
            if (endpoint != null)
            {
                // When doing endpoint routing, MVC does not create filters for any authorization specific metadata i.e [Authorize] does not
                // get translated into AuthorizeFilter. Consequently, there are some rough edges when an application uses a mix of AuthorizeFilter
                // explicilty configured by the user (e.g. global auth filter), and uses endpoint metadata.
                // To keep the behavior of AuthFilter identical to pre-endpoint routing, we will gather auth data from endpoint metadata
                // and produce a policy using this. This would mean we would have effectively run some auth twice, but it maintains compat.
                var policyProvider = PolicyProvider ?? context.HttpContext.RequestServices.GetRequiredService<IAuthorizationPolicyProvider>();
                var endpointAuthorizeData = endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();

                var endpointPolicy = await AuthorizationPolicy.CombineAsync(policyProvider, endpointAuthorizeData);
                if (endpointPolicy != null)
                {
                    builder.Combine(endpointPolicy);
                }
            }

            return builder.Build();
        }

        /// <inheritdoc />
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!context.IsEffectivePolicy(this))
            {
                return;
            }

            // IMPORTANT: Changes to authorization logic should be mirrored in security's AuthorizationMiddleware
            var effectivePolicy = await GetEffectivePolicyAsync(context);
            if (effectivePolicy == null)
            {
                return;
            }

            var policyEvaluator = context.HttpContext.RequestServices.GetRequiredService<IPolicyEvaluator>();

            var authenticateResult = await policyEvaluator.AuthenticateAsync(effectivePolicy, context.HttpContext);

            // Allow Anonymous skips all authorization
            if (HasAllowAnonymous(context))
            {
                return;
            }

            var authorizeResult = await policyEvaluator.AuthorizeAsync(effectivePolicy, authenticateResult, context.HttpContext, context);

            if (authorizeResult.Challenged)
            {
                context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
            }
            else if (authorizeResult.Forbidden)
            {
                context.Result = new ForbidResult(effectivePolicy.AuthenticationSchemes.ToArray());
            }
        }

        IFilterMetadata IFilterFactory.CreateInstance(IServiceProvider serviceProvider)
        {
            if (Policy != null || PolicyProvider != null)
            {
                // The filter is fully constructed. Use the current instance to authorize.
                return this;
            }

            Debug.Assert(AuthorizeData != null);
            var policyProvider = serviceProvider.GetRequiredService<IAuthorizationPolicyProvider>();
            return AuthorizationApplicationModelProvider.GetFilter(policyProvider, AuthorizeData);
        }

        private static bool HasAllowAnonymous(AuthorizationFilterContext context)
        {
            var filters = context.Filters;
            for (var i = 0; i < filters.Count; i++)
            {
                if (filters[i] is IAllowAnonymousFilter)
                {
                    return true;
                }
            }

            // When doing endpoint routing, MVC does not add AllowAnonymousFilters for AllowAnonymousAttributes that
            // were discovered on controllers and actions. To maintain compat with 2.x,
            // we'll check for the presence of IAllowAnonymous in endpoint metadata.
            var endpoint = context.HttpContext.GetEndpoint();
            if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
            {
                return true;
            }

            return false;
        }
    }

代碼中繼承了 IAsyncAuthorizationFilter, IFilterFactory兩個抽象介面,分別來看看這兩個抽象介面的源代碼

IAsyncAuthorizationFilter源代碼如下:
/// <summary>
/// A filter that asynchronously confirms request authorization.
/// </summary>
public interface IAsyncAuthorizationFilter : IFilterMetadata
{
    ///定義了授權的方法
    Task OnAuthorizationAsync(AuthorizationFilterContext context);
}

IAsyncAuthorizationFilter代碼中繼承了IFilterMetadata介面,同時定義了OnAuthorizationAsync抽象方法,子類需要實現該方法,然而AuthorizeFilter中也已經實現了該方法,稍後再來詳細講解該方法,我們再繼續看看IFilterFactory抽象介面,代碼如下:

public interface IFilterFactory : IFilterMetadata
 {
       
    bool IsReusable { get; }

    //創建IFilterMetadata 對象方法
    IFilterMetadata CreateInstance(IServiceProvider serviceProvider);
}

我們回到AuthorizeFilter 源代碼中,該源代碼中提供了四個構造初始化方法同時包含了AuthorizeDataPolicy屬性,我們看看它的預設構造方法代碼

public class AuthorizeFilter : IAsyncAuthorizationFilter, IFilterFactory
{
        public IEnumerable<IAuthorizeData> AuthorizeData { get; }

        //預設構造函數中預設創建了AuthorizeAttribute 對象
        public AuthorizeFilter()
            : this(authorizeData: new[] { new AuthorizeAttribute() })
        {
        }

        //賦值AuthorizeData
        public AuthorizeFilter(IEnumerable<IAuthorizeData> authorizeData)
        {
            if (authorizeData == null)
            {
                throw new ArgumentNullException(nameof(authorizeData));
            }

            AuthorizeData = authorizeData;
        }
}

上面的代碼中預設的構造函數預設給構建了一個AuthorizeAttribute對象,並且賦值給了IEnumerable<IAuthorizeData>的集合屬性;
好了,看到這裡AuthorizeFilter過濾器也是預設構造了一個AuthorizeAttribute的對象,也就是構造了授權所需要的IAuthorizeData信息.
同時AuthorizeFilter實現的OnAuthorizationAsync方法中通過GetEffectivePolicyAsync這個方法獲得有效的授權策略,並且進行下麵的授權AuthenticateAsync的執行
AuthorizeFilter代碼中提供了HasAllowAnonymous方法來實現是否Controller或者Action上標註了AllowAnonymous特性,用於跳過授權
HasAllowAnonymous代碼如下:

private static bool HasAllowAnonymous(AuthorizationFilterContext context)
{
     var filters = context.Filters;
     for (var i = 0; i < filters.Count; i++)
     {
        if (filters[i] is IAllowAnonymousFilter)
        {
           return true;
        }
     }
     //同樣通過上下文的endpoint 來獲取是否標註了AllowAnonymous特性
     var endpoint = context.HttpContext.GetEndpoint();
     if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
     {
        return true;
     }

     return false;
}

到這裡我們再回到全局添加過濾器的方式代碼:

 services.AddControllers(options=>options.Filters.Add(new AuthorizeFilter()));

分析到這裡 ,我很是好奇,它是怎麼全局添加進去的呢?我打開源代碼看了下,源代碼如下:

public class MvcOptions : IEnumerable<ICompatibilitySwitch>
{

        public MvcOptions()
        {
            CacheProfiles = new Dictionary<string, CacheProfile>(StringComparer.OrdinalIgnoreCase);
            Conventions = new List<IApplicationModelConvention>();
            Filters = new FilterCollection();
            FormatterMappings = new FormatterMappings();
            InputFormatters = new FormatterCollection<IInputFormatter>();
            OutputFormatters = new FormatterCollection<IOutputFormatter>();
            ModelBinderProviders = new List<IModelBinderProvider>();
            ModelBindingMessageProvider = new DefaultModelBindingMessageProvider();
            ModelMetadataDetailsProviders = new List<IMetadataDetailsProvider>();
            ModelValidatorProviders = new List<IModelValidatorProvider>();
            ValueProviderFactories = new List<IValueProviderFactory>();
        }

        //過濾器集合
        public FilterCollection Filters { get; }
}

FilterCollection相關核心代碼如下:

public class FilterCollection : Collection<IFilterMetadata>
{
        
        public IFilterMetadata Add<TFilterType>() where TFilterType : IFilterMetadata
        {
            return Add(typeof(TFilterType));
        }

        //其他核心代碼為貼出來
}

代碼中提供了Add方法,約束了IFilterMetadata類型的對象,這也是上面的過濾器中為什麼都繼承了IFilterMetadata的原因。
到這裡代碼解讀和實現原理已經分析完了,如果有分析不到位之處還請多多指教!!!

結論:授權中間件通過獲取IAuthorizeData來獲取AuthorizeAttribute對象相關的授權信息,並構造授權策略對象進行授權認證的,而AuthorizeFilter過濾器也會預設添加AuthorizeAttribute的授權相關數據IAuthorizeData並實現OnAuthorizationAsync方法,同時中間件中通過授權策略提供者IAuthorizationPolicyProvider來獲得對於的授權策略進行授權認證.


您的分享是我們最大的動力!

更多相關文章
  • | 好看請贊,養成習慣 你有一個思想,我有一個思想,我們交換後,一個人就有兩個思想 If you can NOT explain it simply, you do NOT understand it well enough 現陸續將Demo代碼和技術文章整理在一起 "Github實踐精選" ,方便 ...
  • 一、語法 作用:簡化函數代碼 格式:lambda 參數列表 :表達式 P.s: lambda表達式參數可有可無,參數寫法同函數 lambda函數能接收任何數量的參數但只能返回一個表達式的值 def func0(): return 100 func = lambda: 100 # lambda本質是一 ...
  • 從本文開始,將開始介紹關於 Spring 的一些常見知識點。關註我的公眾號「Java面典」,每天 10:24 和你一起瞭解更多 Java 相關知識點。 在如今的 Java Web 開發中,Spring 生態圈占據著巨大的市場份額。幾乎是每個互聯網公司都在用 Spring 生態圈的東西。所以掌握Spr ...
  • 引言:搭建微服務架構就像是買電腦,使用SpringCloud就是在買品牌機。 前言 昂,美好的天氣里,不想直接說技術,給小伙伴萌看看傍晚的天空吧。 —— 能找到天上的北極星嗎? 上一篇文章中,通過一個簡單的小故事,輕鬆愉快的講解了架構的演變,以及為啥會有微服務,什麼是微服務。不過在最後留下了一個小疑 ...
  • 原創聲明 本文作者:黃小斜 轉載請務必在文章開頭註明出處和作者。 本文思維導圖 什麼是Spring,為什麼你要學習spring? 你第一次接觸spring框架是在什麼時候?相信很多人和我一樣,第一次瞭解spring都不是做項目的時候用到,而是在網上看到或者是聽到過一個叫做spring的框架,這個框架 ...
  • 前言 虛繼承 是面向對象編程中的一種技術,是指一個指定的基類,在繼承體繫結構中,將其成員數據實例共用給也從這個基類型直接或間接派生的其它類。 虛擬繼承是多重繼承中特有的概念。虛擬基類是為解決多重繼承而出現的。 虛擬繼承在一般的應用中很少用到,所以也往往被忽視,這也主要是因為在C++中,多重繼承是不推 ...
  • 在上一篇abp(net core)+easyui+efcore實現倉儲管理系統——入庫管理之四(四十)文章中我們已經定義了應用的介面,併在應用層實現了這些介面。接下來我們要在展示層來實現入庫單的列表功能。 ...
  • 在微信開發H5頁面的時候,往往藉助於WeUI或者Jquery WeUI等基礎上進行界面效果的開發,由於本人喜歡在Asp.net的Web界面上使用JQuery,因此比較傾向於使用 jQuery WeUI,本篇隨筆結合官方案例和自己的項目實際開發過程的經驗總結,對在H5頁面開發過程中設計到的界面控制項進行... ...
一周排行
  • 在上篇文章中我們已經知道了多線程是什麼了,那麼它到底可以幹嘛呢?這裡特別聲明一個前面的委托沒看的同學可以到上上上篇博文查看,因為多線程要經常使用到委托。源碼 一、非同步、同步 1.同步(在計算的理解總是要你措不及防,同步當線程做完一件事情之後,才會執行後續動作),同步方法慢,只有一個線程執行,非同步方法 ...
  • 本文主要是講解stopwatch對程式運行時間的準確測量 僅僅介紹裡面的StartNew()方法,Restart()方法和ElapsedMilliseconds { get;}屬性 public void StartNew():作用是對新的 System.Diagnostics.Stopwatch ...
  • 一、引言 RabbitMQ是Rabbit Message Queue的簡寫,但不能僅僅理解其為消息隊列,消息代理更合適。RabbitMQ是一個由 Erlang 語言開發的AMQP(高級消息隊列協議)的開源實現,其內部結構如下: RabbitMQ作為一個消息代理,主要和消息打交道,負責接收並轉發消息。 ...
  • TerminalMACS(Terminal Manager And Check System) 遠程終端管理和檢測系統 本文同步更新地址:https://dotnet9.com/11429.html 一、本系統可監控多種終端資源: 移動端 Android iOS PC端 Windows Linux ...
  • 首先,好消息是Goole將於2020年2月份發佈Chrome 80版本。本次發佈將推進Google的“漸進改良Cookie”策略,打造一個更為安全和保障用戶隱私的網路環境。 壞消息是,本次更新可能導致瀏覽器無法向服務端發送Cookie。如果你有多個不同功能變數名稱的應用,部分用戶很有可能出現會話時常被打斷的 ...
  • 在偶然一次調試某程式時,遇到提示: 無法載入程式集*****.XmlSerializers.dll,文件找不到(Could not load file or assembly ****.XmlSerializers.dll , FileNotFoundException...)。於是嘗試在項目屬性中 ...
  • 在上一篇abp(net core)+easyui+efcore實現倉儲管理系統——入庫管理之五(四十一) 文章中實現了入庫管理的列表頁面,並實現了控制器的代碼。在今天我們學習如何在前端實現新增入庫單信息界面。 ...
  • 面向對象 面向對象是一個抽象的概念,其本質就是對事物以抽象的方式建立對應的模型。 簡單來講,比如我有一隻鋼筆,那麼我就可以通過分析,可以得到 這隻鋼筆的材第是塑料,品牌是個雜牌 ,裡面裝的墨是黑色的,可以用。這時候就能建立一個鋼筆的模型,它在這裡應該有這些屬性: 圖是一個不正確的UML類圖,但是可以 ...
  • 在ASP.NET MVC中有四種過濾器類型 Action 1、在ASP.NET MVC項目中,新建文件夾Filter,然後新建類MyCustormFilter,繼承自ActionFilterAttribute類,我們來看下ActionFilterAttribute類有如下四個方法,從命名我應該就可以 ...
  • 你需要瞭解的 HTTP Status Code Intro 現在前後端分離的開發模式越來越流行,後端負責開發對應的 API,前端只需要 關註前端頁面的數據展示和前端邏輯即可。 對於前後端分離這種開發模式,我個人還是比較喜歡的,因為這樣可以讓更專業的人做更專業的事情,後端專註於做 API 的開發設計, ...
x