主頁 > .NET開發 > Asp.Net Core Authorize你不知道的那些事(原始碼解讀)

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

2020-09-16 04:00:11 .NET開發

一、前言

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 = https://www.cnblogs.com/jlion/p/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 = https://www.cnblogs.com/jlion/p/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() ?? Array.Empty();
            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();

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

            // Allow Anonymous skips all authorization
            if (endpoint?.Metadata.GetMetadata() != 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 = https://www.cnblogs.com/jlion/p/endpoint?.Metadata.GetOrderedMetadata() ?? Array.Empty();

前面我分享過一篇關于 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 =https://www.cnblogs.com/jlion/p/= null)
            {
                throw new ArgumentNullException(nameof(authorizeData));
            }

            AuthorizeData = authorizeData;
        }

        /// 
        /// Initializes a new instance of .
        /// 
        /// The name of the policy to require for authorization.
        public AuthorizeFilter(string policy)
            : this(new[] { new AuthorizeAttribute(policy) })
        {
        }

        /// 
        /// The  to use to resolve policy names.
        /// 
        public IAuthorizationPolicyProvider PolicyProvider { get; }

        /// 
        /// The  to combine into an .
        /// 
        public IEnumerable AuthorizeData { get; }

        /// 
        /// Gets the authorization policy to be used.
        /// 
        /// 
        /// Ifnull, the policy will be constructed using
        /// .
        /// 
        public AuthorizationPolicy Policy { get; }

        bool IFilterFactory.IsReusable => true;

        // Computes the actual policy for this filter using either Policy or PolicyProvider + AuthorizeData
        private Task 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 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 = https://www.cnblogs.com/jlion/p/endpoint.Metadata.GetOrderedMetadata() ?? Array.Empty();

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

            return builder.Build();
        }

        /// 
        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 =https://www.cnblogs.com/jlion/p/= 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來獲得對于的授權策略進行授權認證.

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/52856.html

標籤:.NET Core

上一篇:AspNetCore3.1_Secutiry原始碼決議_5_Authentication_OAuth

下一篇:EF Core資料訪問入門

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more