C#web服务开发

1、Program.cs声明程序入口static main()函数,用startup内方法创建和初始化web类对象

      Startup.cs初始化内容,涉及路由设计和服务绑定、依赖注入等全局初始化,实现主要两个配置初始化方法

              // This method gets called by the runtime. Use this method to add services to the container.
              public void ConfigureServices(IServiceCollection services)

              和

              // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
              public void Configure(IApplicationBuilder app, IHostingEnvironment env)

2、web服务添加

IServiceCollection services

services.AddSingleton();//方法创建一个Singleton服务,首次请求会创建服务,然后,所有后续的请求中都会使用相同的实例,整个应用程序生命周期都使用该单个实例

services.AddScoped();//不同http清求,实例不同,同名谓词不同,也不行。例如httpget跟httppost,作用域是一定范围内,例如从同一个post请求的create方法,只能统计一次,每次请求都是新的实例

services.AddTransient();//临时服务,每次请求时,都会创建一个新的Transient服务实例

services.AddControllersWithViews(option =>
                {
                    option.Filters.Add<AuthorizationFilter>();
                }).AddNewtonsoftJson();//添加MVC框架服务,绑定过滤认证信息方法,绑定json格式输入输出

services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "MsSystem API",
                    Description = "RESTful API for My Web Application",
                    //TermsOfService = null,
                });

                //Determine base path for the application.  
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //Set the comments path for the swagger json and ui.  
                var xmlPath = Path.Combine(basePath, "Host.xml");
                options.IncludeXmlComments(xmlPath);
            });//swagger自动生成接口文档

3、http请求信息类ActionContext,派生多种处理类供controller解析信息处理

授权过滤器,认证信息检查,AuthorizationFilterContext  继承  FilterContext  继承  ActionContext

//特性声明 [NoLogin]使用
public class NoLoginAttribute : Attribute
{
}

public class AuthorizationFilter : IAsyncAuthorizationFilter
{
	public Task OnAuthorizationAsync(AuthorizationFilterContext context)
	{
        //检查调用者controller的Attribute属性有无NoLogin
		if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
		{
			var noNeedLoginAttribute = controllerActionDescriptor.
							   ControllerTypeInfo.
							   GetCustomAttributes(true)
							   .Where(a => a.GetType().Equals(typeof(NoLoginAttribute)))
							   .ToList();
			noNeedLoginAttribute.AddRange(controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
							 .Where(a => a.GetType().Equals(typeof(NoLoginAttribute))).ToList());

			//如果标记了 NoLoginAttribute 则不验证其登录状态
			if (noNeedLoginAttribute.Any())
			{
				return Task.CompletedTask;
			}
		}

		var token = context.HttpContext.Request.Headers["token"].ToString();
		if (!token.IsNullOrWhiteSpace())
		{
			var time = token.DES3Decrypt().ToDateTime();
			//登录信息有效期为当天
			if (DateTime.Now.Date == time.Date)
			{
				return Task.CompletedTask;
			}
		}

		context.Result = new JsonResult(new
		{
			ErrorMsg = "请登录",
			ResultUrl = "/signin",
		});
		context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
		return Task.CompletedTask;
	}
}

swagger生效,在startup的配置方法内public void Configure(IApplicationBuilder app, IHostingEnvironment env)

app.UseSwagger();
app.UseSwaggerUI(c =>
 {
       c.SwaggerEndpoint("/swagger/v1/swagger.json", "MsSystem API V1");
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值