相关疑难解决方法(0)

.NET Core中的CORS

我试图以这种方式在.NET Core中启用CORS:

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                    .AllowAnyMethod()
                                                                     .AllowAnyHeader()));     
        services.AddMvc();            
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("AllowAll");

        app.UseMvc(routes =>
         {
             routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
         });

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我向Angular 2发送请求到我的应用程序时,我得到了名人

"请求的资源上没有'Access-Control-Allow-Origin'标头."

错误信息.

我也使用Windows身份验证+ WebListener.如果我与邮递员核对,唯一的响应标题是:

Content-Length→3533 Content-Type→application/json; charset = utf-8日期→星期五,2016年10月14日12:17:57 GMT服务器→Microsoft-HTTPAPI/2.0

所以必须仍然配置错误.有什么建议?

如果我删除了outcommented行它,但我需要Windows身份验证:-(

        var host = new WebHostBuilder()
            .UseWebListener()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            //.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
            .Build();
Run Code Online (Sandbox Code Playgroud)

c# cors web .net-core

40
推荐指数
6
解决办法
4万
查看次数

如何在 ASP.NET Core 6.0 Web API 项目中启用 cors?

在我的 ASP.NET Core 6.0 Web API 项目中配置了 CORS。但预检请求收到 http 405 错误。

换句话说,不允许使用 HTTP OPTION。看起来 cors 没有启用。

我看过示例,但此项目模板中config.EnableCors();没有。App_Start/WebApiConfig.cs

我在这里缺少什么?

程序.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var devCorsPolicy = "devCorsPolicy";
builder.Services.AddCors(options =>
{
    options.AddPolicy(devCorsPolicy, builder => {
        //builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
        //builder.SetIsOriginAllowed(origin => true);
    });
});


var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseCors(devCorsPolicy);
}
else 
{ …
Run Code Online (Sandbox Code Playgroud)

c# cors asp.net-core-webapi asp.net-core-6.0

31
推荐指数
3
解决办法
9万
查看次数

如何在docker机器内外使用IdentityServer4?

我希望能够从docker机器外部和内部对Identity Server(STS)进行身份验证.

我在设置容器内外的正确权限时遇到问题.如果我将权限设置为内部名称,mcoidentityserver:5000则API可以进行身份​​验证,但客户端无法获取令牌,因为客户端位于docker网络之外.如果我将权限设置为外部名称,localhost:5000则客户端可以获取令牌,但API无法识别权限名称(因为localhost在这种情况下是主机).

我该如何设置权限?或许我需要调整码头网络?

红色箭头是我遇到麻烦的部分. 网络中的三个docker容器,一个客户端和PostgreSQL Admin,它们的端口和一个红色箭头显示我认为问题所在.

详情

我正在设置一个Windows 10 docker开发环境,它使用ASP.NET Core API(在Linux上),Identity Server 4(Linux上的ASP.NET Core)和PostgreSQL数据库.PostgreSQL不是问题,包含在图表中以保证完整性.它被映射到9876,因为我现在还在主机上运行了一个PostgreSQL实例.mco是我们公司的简称.

我一直在遵循Identity Server 4的说明来启动和运行.

我不包括docker-compose.debug.yml它,因为它运行的命令只与在Visual Studio中运行相关.

泊坞窗,compose.yml

version: '2'

services:
mcodatabase:
    image: mcodatabase
    build:
    context: ./Data
    dockerfile: Dockerfile
    restart: always
    ports:
    - 9876:5432
    environment:
    POSTGRES_USER: mcodevuser
    POSTGRES_PASSWORD: password
    POSTGRES_DB: mcodev
    volumes:
    - postgresdata:/var/lib/postgresql/data
    networks:
    - mconetwork

mcoidentityserver:
    image: mcoidentityserver
    build:
    context: ./Mco.IdentityServer
    dockerfile: Dockerfile
    ports:
    - 5000:5000
    networks:
    - mconetwork

mcoapi: …
Run Code Online (Sandbox Code Playgroud)

docker docker-compose identityserver4

22
推荐指数
2
解决办法
3631
查看次数

在Asp.NET中为选项预检请求添加'access-control-allow-origin'响应

我在Chrome中遇到以下错误:

对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.原产地" 的http://本地主机:9000 "因此不允许访问.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseIISPlatformHandler();

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseCors(policy => policy
       .WithOrigins("http://localhost:9000")
       .AllowAnyMethod()
       .WithHeaders("Access-Control-Allow-Origin, Content-Type, x-xsrf-token, Authorization")
       .AllowCredentials());

    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

根据chrome,没有一个标题被添加到响应中.

access-control-allow-origin在Asp.NET 5 中将标题添加到选项响应的正确方法是什么?

asp.net asp.net-mvc cors asp.net-core

11
推荐指数
2
解决办法
6186
查看次数

.NET 6.0 Web API 中的 CORS

我有一个使用 Axios 调用 .NET 6 Web API 的 React 应用程序。

在program.cs文件中,我添加了builder.Services.AddCors和app.UseCors,如下所示。

但我仍然收到 CORS 错误和 404 预检。

该方法适用于 .NET 5 Web Api。

我们需要为 .NET 6 Web Api 设置什么吗?

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
<removed>

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors();

// Add services to the container.
<removed>

// App settings
<removed>

<removed>

builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
    });

// AutoMapper
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

<removed>

// Firebase
<removed>

var app = builder.Build();
Run Code Online (Sandbox Code Playgroud)

CORS …

c# webapi .net-6.0

9
推荐指数
1
解决办法
2万
查看次数

ASP.NET Core CORS请求被阻止;我的API为什么不应用正确的标头?

尝试通过身份验证设置CORS。我在http:// localhost:61000上有一个Web API网站,在http:// localhost:62000上有一个正在使用的Web应用程序。在Web API Startup.cs中,我具有:

 public void ConfigureServices(IServiceCollection services)
 {
        services.AddCors(o => o.AddPolicy("MyPolicy", corsBuilder =>
        {
            corsBuilder.WithOrigins("http://localhost:62000")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
        }));
        IMvcBuilder builder = services.AddMvc();
        // ...
}

// ...

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        app.UseCors("MyPolicy");
        app.UseDeveloperExceptionPage();
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

所有的说明似乎表明这应该是我所需要的。在应用的Javascript中,我调用:

    $.ajax({
        type: 'POST',
        url: "http://localhost:61000/config/api/v1/MyStuff",
        data: matchForm.serialize(),
        crossDomain: true,
        xhrFields: { withCredentials: true },
        success: function (data) {
            alert(data);
        }
    });
Run Code Online (Sandbox Code Playgroud)

我进入Chrome: Failed to load http://localhost:61000/config/api/v1/MyStuff: No 'Access-Control-Allow-Origin' header is present …

cross-site asp.net-core

8
推荐指数
1
解决办法
6789
查看次数

404 for web.api cors OPTIONS

我已按照通常的步骤在web.api中启用cors,但在Chrome和Firefox中获得了对OPTIONS请求的404响应 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mydomain.com/api/1/widgets. This can be fixed by moving the resource to the same domain or enabling CORS.

在我的WebApiConfig.cs中,我得到了:

var enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(enableCorsAttribute);
Run Code Online (Sandbox Code Playgroud)

我也尝试将EnableCors属性添加到特定的控制器或操作,并且都具有相同的结果.

我还在web.config中添加了以下内容:

<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule" />
</modules>
<handlers>
    <remove name="WebDAV" />
...
Run Code Online (Sandbox Code Playgroud)

这是我的javascript:

$.ajax({
    url: 'https://api.mydomain.com/api/1/widgets',
    type: "GET",
    headers: {
        Accept: "text/html; charset=utf-8",
        Authorization: 'Bearer ???????????????????????????????'
            }
        });
Run Code Online (Sandbox Code Playgroud)

但Chrome的响应为404,Firefox中的"Cross-Origin请求已被阻止".

以下是我的chrome开发人员工具栏中失败请求的详细信息:

Remote Address:??.???.???.???:443
Request URL:https://api.mydomain.com/api/1/widgets
Request Method:OPTIONS
Status Code:404 …
Run Code Online (Sandbox Code Playgroud)

c# asp.net http cors asp.net-web-api

7
推荐指数
1
解决办法
6046
查看次数

Asp.NET MVC Core CORS

我们正在开发具有移动部件和Web UI的应用程序.Web UI使用angular,我们在后端配置cors时遇到问题.我们的代码看起来像这样(只是对我们的问题很重要的代码):

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("AllowAll");

    app.UseMvc();
}

public void ConfigureServices(IServiceCollection services)
{            
    services.AddMvc();

    //Add Cors support to the service
    services.AddCors(
        options => options.AddPolicy(
            "AllowAll", p => p.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
            )
        );
}
Run Code Online (Sandbox Code Playgroud)

从stackoverflow上的文档和其他帖子,这应该工作,但不是.我们错过了什么?

日Thnx


编辑:

这是POSTMAN的请求:

卷曲' https://guw.azurewebsites.net/api/token ' -X选项-H '杂注:无缓存' -H '访问控制请求-方法:POST' -H"来源: HTTP:// localhost:9000' -H'Eccept-Encoding:gzip,deflate,sdch,br'-H'Accept-Language:en-US,en; q = 0.8'-H'User-Agent:Mozilla/5.0(Windows NT 10.0 ; WOW64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/51.0.2704.103 Safari/537.36'-H'接受:/ ' - H'缓存控制:无缓存'-H'参考:http:// localhost: 9000 / '-H'连接:keep-alive'-H'Access-Control-Request-Headers:接受,授权,内容类型' - 压缩

你可以在邮递员中导入它并查看它.此请求由angular app发送.

希望这可以帮助.

最后我决定在我的中间件中添加这个方法:

private …
Run Code Online (Sandbox Code Playgroud)

cors asp.net-core-mvc asp.net-core

6
推荐指数
1
解决办法
2752
查看次数

如何解决 401 角度未经授权的问题?

我创建了 .Net Core API 并配置了 Windows 身份验证。在我的 angular 应用程序中,我必须在每个请求中添加此选项withCredentials : true。我做了一个放置请求,但它返回给我:

401(未授权) 401未授权 401网络

我也尝试发布请求,但它不起作用,只能获取请求工作。

auth.service.ts :

updateUser(id,lastlogin,ac,lastlogoff,picture){
  return this.http.put(`${this.config.catchApiUrl()}User/`+ id , {
    id : id ,
    picture : picture,
    lastLogin : lastlogin ,
    lastLogoff : lastlogoff ,
    ac: ac
  },{
    headers : this.header,
    withCredentials : true
  })
}
Run Code Online (Sandbox Code Playgroud)

auth.component.ts :

constructor(
private authService : AuthenticationService
) { }

loginToApplication(username :string){
    this.authService.updateUser(e["id"],lastLogin,e["ac"],e["lastLogoff"],e["picture"]).subscribe(
        console.log("enter"))
}
Run Code Online (Sandbox Code Playgroud)

.Net Core API 更新用户控制器:

[AllowAnonymous] // Even if I do this it doesn't work
[HttpPut("{id}")]
public …
Run Code Online (Sandbox Code Playgroud)

put windows-authentication angular asp.net-core-2.1

6
推荐指数
1
解决办法
6690
查看次数

React、Fetch-API、no-cors、不透明响应,但仍在浏览器内存中

我一直在尝试创建一个 React 站点,它会从 API 获取 GET 响应并将其打印到我的 .html 文件中。我已经成功地正确获取了文件,但无法访问服务器发送给我的 JSON 数据。

如果我在 Fetch 请求中使用 no-cors,我会得到一个几乎不包含任何内容的不透明响应,但如果我转到开发人员工具,我可以在那里找到我的数据并读取它。如果我确实使用 cors,几乎同样的事情。我收到 403 错误,但我的数据位于浏览器内存中,但我的代码未将其打印出来。我可以在开发者工具中找到网络的回复。

为什么服务器给我一个错误,但我仍然得到我的数据?如果它在浏览器中,我该如何访问它?

class Clock extends React.Component {
    constructor(props) {
        super(props)
          this.state = {data2: []}
          this.apihaku = this.apihaku.bind(this)
     }

     componentDidMount() {
         this.apihaku(),
         console.log("Hei")
     }

     apihaku () {
         fetch('https://#######/mapi/profile/',
         {method: 'GET', mode:'no-cors', credentials: 'include',
         headers: {Accept: 'application/json'}}
         ).then((response) => {
              console.log(response);
              response.json().then((data) =>{
              console.log(data);
         });
    });
}

render() {
    return <div>
        <button>Button</button>
    </div>
}}

ReactDOM.render(
   <Clock />,
       document.getElementById('content')
)
Run Code Online (Sandbox Code Playgroud)

编辑:尝试建议后出现错误图像

https://i.stack.imgur.com/wp693.png

https://i.stack.imgur.com/07rSG.png

https://i.stack.imgur.com/XwZsR.png

reactjs fetch-api

5
推荐指数
1
解决办法
2万
查看次数