Asp.Net Core AuthorizeAttribute 和AuthorizeFilter 跟进及源码解读

一、前言

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;           //不需要httpsoptions.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 runprivate 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 constructorvar policyEvaluator = context.RequestServices.GetRequiredService<IPolicyEvaluator>();var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);// Allow Anonymous skips all authorizationif (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null){await _next(context);return;}// Note that the resource will be null if there is no matched endpointvar 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 + AuthorizeDataprivate 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 filtervar 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 providerbuilder.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 AuthorizationMiddlewarevar 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 authorizationif (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() }){}//赋值AuthorizeDatapublic 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来获得对于的授权策略进行授权认证.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/310913.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1张手稿图讲明白 Kubernetes 是怎么运行的

注意&#xff1a;如果您已经知道Kubernetes的工作原理&#xff0c;那么您可能会对我之前的博文感兴趣&#xff0c;请停止使用具有管理员权限的kubeconfigKubernetes是最初由Google设计的开源工具&#xff0c;现在由 Cloud Native Computing Foundation&#xff08;CNCF&#xf…

就喜欢用vSphere部署K8s集群,不全是因为自动化!

通过努力&#xff0c;我们有了一个完整配置的工作负载域&#xff0c;其中包括一个NSX-T Edge部署。现在&#xff0c;我们准备继续使用Kubernetes 部署vSphere。通过VMware Cloud Foundation 4.0中的SDDC Manager&#xff0c;我们确保NSX-T Edge可用&#xff0c;并且还确保Workl…

同源策略_如何支持跨域

欢迎大家阅读《朝夕Net社区技术专刊》我们致力于.NetCore的推广和落地&#xff0c;为更好的帮助大家学习&#xff0c;方便分享干货&#xff0c;特创此刊&#xff01;很高兴你能成为忠实读者&#xff0c;文末福利不要错过哦&#xff01;01PARTCoreWebApi的调用1.在Core MVC下建立…

企业数字化转型解决方案

2020年国务院常务会议明确指出&#xff0c;依托工业互联网促进传统产业加快上线上云。此前&#xff0c;工信部也在全国工业和信息化工作会议上表示&#xff0c;2020年要实施“5G工业互联网”512工程。和5G、人工智能等同列的“新基建”&#xff0c;工业互联网成为数字时代的基础…

网站 asp和php的用途,asp和php都有什么功能?

ASP是什么&#xff1f;有什么功能&#xff1f;ASP.NET是微软开发&#xff0c;建立动态的&#xff0c;强大的&#xff0c;智能的、可扩展的网站和网际网络应用的全功能的程序语言如C或VB.NET #。它包括一个强大的安全评估的亮点&#xff0c;以及一个组织的小工具&#xff0c;可以…

ASP.NET Core 3.x - Endpoint Routing 路由体系的内部机制

Endpoint是什么&#xff1f;Endpoint简单的可以理解为这样的一些类&#xff0c;它们包含一个请求的委托&#xff08;Request Delegate&#xff09;和其它的一些元数据&#xff0c;使用这些东西&#xff0c;Endpoint类可以生成一个响应。而在MVC的上下文中&#xff0c;这个请求委…

java获取主机信息大全,网络编程:Java获取网络主机信息

java.net.InetAddress类表示互联网协议 (IP) 地址。有两个子类&#xff1a;Inet4Address&#xff0c; Inet6Address通过 InetAddress可以方便获取一个域名下的IP&#xff0c;也可以获取一个IP的主机名。下面是例子&#xff0c;通过程序查看51cto主机的IP信息&#xff0c;51cto是…

【项目升级】单库、多库、读写分离 · 任你选

本期配套视频&#xff1a;https://www.bilibili.com/video/BV1BJ411B7mn?p6&#xff08;点击阅读原文&#xff0c;可看&#xff0c;如果没有&#xff0c;最晚下午可看&#xff09;继上周增加【任务调度】以后&#xff0c;继续对项目进行2.0版本升级&#xff0c;其实改动的地方…

.Net微服务实战之技术选型篇

王者荣耀 去年我有幸被老领导邀请以系统架构师的岗位带技术团队&#xff0c;并对公司项目以微服务进行了实施。无论是技术团队还是技术架构都是由我亲自的从0到1的选型与招聘成型的&#xff0c;此过程让我受益良多&#xff0c;因此也希望在接下来的系列博文尽可能的与大家分享…

autohotkey php,Autohotkey+php实现免浏览器听录音

环境说明&#xff1a;Elastix 2.5ln -s /var/spool/asterisk/monitor /var/www/html/接口文件(php)&#xff1a;$conmysql_connect("localhost","root","passwd");if(!$con) echo "没有连接成功!";mysql_select_db("asteriskcdrd…

.NET Core开发实战(第32课:集成事件:解决跨微服务的最终一致性)--学习笔记...

32 | 集成事件&#xff1a;解决跨微服务的最终一致性首先看一下集成事件的工作原理它的目的时为了实现系统的集成&#xff0c;它主要是用于系统里面多个微服务之间相互传递事件集成事件的实现方式有两种&#xff0c;一种是图上显示的发布订阅的方式&#xff0c;通过 EventBus&a…

Dapper操作MySQL数据库获取JSON数据中文乱码

在项目中利用Dapper将JSON数据存储到MySQL数据库&#xff0c;结果发现JSON数据中的中文乱码&#xff0c;特此记录&#xff0c;希望对存储JSON的童鞋能有所帮助&#xff0c;文中若有错误之处&#xff0c;还望批评指正。为了引出最终问题出在什么地方&#xff0c;我们重头开始进行…

C++set容器去重法

给出一个10位数&#xff0c;它如果每个位的数都把0-9这10个数都只用了一次&#xff0c;就输出yes&#xff0c;否则输出no #include <iostream> #include <set> using namespace std; set<int>s; typedef long long LL;int main() {LL n;while (cin >>…

流传在程序员中的传说,你知道几个?

在号称从事高薪新 科技工作的程序员周遭流传着许多与他们单纯气质不符的传说在这些被神秘面纱笼罩的人群中即使是从事着同一工种都有着许许多多科学无法解释的差异老程序员们对此讳莫如深新程序员们却有时感到惶恐不安...这背后究竟是道德的扭曲还是人性的沦丧倒是都并不至于只…

C++关于getline()和getchar()的小点

getchar只能“吃”一个字符&#xff0c;而getline可以“吃”一行字符 代码如下: #include <iostream> #include <cstring> using namespace std;int main() {char c;cin>>c;string line;getline(cin,line);cout<<c<<endl;cout<<line<…

谁说docker-compose不能水平扩展容器、服务多实例?

❝虽说我已经从docker-compose走上了docker swarm的邪门歪道&#xff0c;目前被迫走在k8s这条康庄大道&#xff0c; 但是我还是喜欢docker-compose简洁有效的部署方式。❞曾其何时docker-compose非常适合开发、测试、快速验证原型&#xff0c;这个小工具让单机部署容器变得简洁…

.NET Core开发实战(第33课:集成事件:使用RabbitMQ来实现EventBus)--学习笔记(上)...

33 | 集成事件&#xff1a;使用RabbitMQ来实现EventBus这一节我们来讲解如何通过 CAP 组件和 RabbitMQ 来实现 EventBus要实现 EventBus&#xff0c;我们这里借助了 RabbitMQ&#xff0c;它的整个安装和使用的体验是非常人性化的&#xff0c;如果是在 Windows 下开发的话&#…

nginx php iconv,Nginx +PHP部署一

Nginx PHP部署一Alvin.zeng目录一、安装PHP1、Yum安装需要的包yum -y install gcc gcc-c autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurs…

以Blog.Core的方式来打开Abp.vNext

&#xff08;发现Abp这个logo真像佐助写轮眼&#xff09;最近自己的框架已经基本的成型了&#xff0c;当然还有很多质疑的地方&#xff0c;比如这些人是这么说的&#xff0c;基本都是原文&#xff1a;你的教程太乱了&#xff0c;和框架代码都不一样&#xff08;&#xff1f;&am…

算法题目中常见的几种输入小点-gets,cin,scanf,getline,sstream

cin,scanf遇到空格都会停下来。gets可读入空格 例如: 在这里由于要读入空格&#xff0c;我们用gets来读入。 const int N 8; char g[N][N];while(gets(g[0])!NULL) {gets(g[1]);}C关于getline()和getchar()的小点C stringstream输入方式下面这两段代码要注意一下: const in…