分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

CORS FOR AspNetCore

发布时间:2023-09-06 01:33责任编辑:白小东关键词:暂无标签

废话:

以前总是看别人博客,但是连评论都懒得给一个,于是心有愧疚,开始写写东西。本人不是科班出生的CODER,只是看多了,懂一些,了解一些思想,也不会动手CODING,也就把看到的换种话记录下来。最近了解了一下asp.net core 的pipeline,认识了CORS,这篇文章就是把关于CORS的Microsoft知识文档用自己的话翻译一下。

正文:

参考:

https://docs.microsoft.com/en-us/aspnet/core/security/cors

 CORS(Cross Origin Resource Sharing),是一种跨域资源共享方式,由于浏览器“same-origin"(同源同策)的限制,其在实际应用中产生,同是W3C标准

至于何为SAME-ORIGIN:

  1. 协议相同,比如http、https、file等
  2. 域相同,比如www.baiud.com
  3. 端口相同

如何使用CORS

使用方法一:全局应用

.net core 的CORS模块位于Microsoft.AspNetCore.Cors的nuget包

在asp.net core 中的services和middleware配置CORS

添加引用:

using Microsoft.AspNetCore.Cors

startup.cs

public void ConfigurationServices(IserviceCollection services){ ???services.AddCors()}public void Configure(IApplicationBuilder app,IHostingEnviroment env,ILoggerFactory loggerFactory){  app.UseCors(builder=>    builder.WithOrigins("http://localhost:5000”);  );}

 注意:

  1. AddCors()优先于其他任何服务
  2. builder.WithOrigins(url)的参数不能以‘/’结尾
  3. builder有一些chain method ,是用于过滤请求的,可自行查阅

使用方法二:命名使用

先定义一个或多个CORS策略,在controller、class、function等对象上根据策略名字,在attribute中使用

startup.cs

public void ConfigureServices(IServiceCollection services){ ???services.AddCors(options => ???{ ???????options.AddPolicy("AllowAOrigin", ???????????builder => builder.WithOrigins("http://example.com")); ???????options.AddPolicy("AllowBOrigin", ???????????builder => builder.WithOrigins("http://example.com"))  }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {   app.UseCors("AllowAOrigin");}//如果是MVC APP,只需要add service,不需要配置middleware

在attribute中使用CORS

[HttpGet][EnableCors("AllowSpecificOrigin")]public IEnumerable<string> Get(){ ???return new string[] { "value1", "value2" };}

 限制所有controller

public void ConfigureServices(IServiceCollection services){ ???services.AddMvc(); ???services.Configure<MvcOptions>(options => ???{ ???????options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAOrigin")); ???});}

 到这里CORS基本用法差不多了,细节之处可见官网文档,英语好的可以自行看英文文档.至于这个东西在实际什么项目中怎么应用我也不清楚,不过我用在分离前后端上倒是好用。

CORS FOR AspNetCore

原文地址:https://www.cnblogs.com/wellsyu/p/8146499.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved