.Net Core API上的CORS从axios请求返回401未经授权

.Net Core API上的CORS从axios请求返回401未经授权,cors,.net-core,axios,identityserver3,identityserver4,Cors,.net Core,Axios,Identityserver3,Identityserver4,我想做的事 我想从React前端向我的API发送补丁请求。API使用Identity Server 4验证请求 发生了什么事 请求工作并通过邮递员的控制器,但当它从我的前端发出时,它不工作。当来自axios请求时,它抛出未经授权的响应 另外,get请求在前端非常有效。get方法也受Identity Server的保护 邮差请求 http://localhost:90909/api/products/3434 Headers = { Authorization: Bea

我想做的事

我想从React前端向我的API发送补丁请求。API使用Identity Server 4验证请求

发生了什么事

请求工作并通过邮递员的控制器,但当它从我的前端发出时,它不工作。当来自axios请求时,它抛出未经授权的响应

另外,get请求在前端非常有效。get方法也受Identity Server的保护

邮差请求

http://localhost:90909/api/products/3434

    Headers =  { 
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body: 
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]
General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}
CORS设置

services.AddCors(options =>
            {

                options.AddPolicy("JSClient", builder =>
                    builder.WithOrigins("http://localhost:9999")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
日志

我启用了一些日志。这里有一些我已经看过了

下面是我从现在得到的

飞行前

http://localhost:90909/api/products/3434

    Headers =  { 
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body: 
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]
General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}
以下错误似乎发生在CORS的飞行前检查期间

System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\My Site Projects\TestProjects\InventoryApi\AnotherLoggingMiddleware.cs:line 43
Exception thrown: 'System.InvalidOperationException' in InventoryApi.dll
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-11-15T03:42:56.0180842Z","tags":{"ai.internal.nodeName":"yay-PC","ai.operation.id":"0HL9BRASKOUFU:00000003","ai.application.ver":"1.0.0.0","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.name":"OPTIONS /api/products/1020","ai.location.ip":"127.0.0.1","ai.cloud.roleInstance":"yay-PC"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"An unhandled exception has occurred while executing the request","severityLevel":"Error","properties":{"{OriginalFormat}":"An unhandled exception has occurred while executing the request","DeveloperMode":"true","CategoryName":"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware","AspNetCoreEnvironment":"Development","Exception":"System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\\My Site Projects\\TestProjects\\InventoryApi\\AnotherLoggingMiddleware.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()"}}}}
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request
这是飞行前请求的401响应

http://localhost:90909/api/products/3434

    Headers =  { 
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body: 
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]
General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}

获取请求的服务器需要启用访问权限

例如,在apache服务器上,在配置文件中添加标题集Access Control Allow-Origin

<Directory />
        Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
</Directory>

标题集访问控制允许原点“http://ipaddress:[端口]”
来源地在提供react服务的地方

邮递员很可能被配置为允许任何来源访问


获取请求的服务器需要启用访问权限

例如,在apache服务器上,在配置文件中添加标题集Access Control Allow-Origin

<Directory />
        Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
</Directory>

标题集访问控制允许原点“http://ipaddress:[端口]”
来源地在提供react服务的地方

邮递员很可能被配置为允许任何来源访问


嘿,对不起,我忘了添加设置。但是我通过启用特定地址在api级别上进行了设置。我编辑了postHey,对不起,我忘了添加我的设置。但是我通过启用特定地址在api级别上进行了设置。我编辑了这篇文章