gpt4 book ai didi

来自原点的 Angular 和 WebApi Cors 请求已被 CORS 策略阻止

转载 作者:行者123 更新时间:2023-12-02 18:39:25 26 4
gpt4 key购买 nike

我有一个 Angular 应用程序( Angular 版本 Angular CLI:8.3.26节点:10.13.0操作系统:win32 x64 Angular :8.2.14)

在environment.ts中我有与我的后端的链接

    export const environment = {
baseUrlNG: 'http://localhost:4200/',
baseUrlApi: 'http://localhost:8082/backend/api/'
}

后端是一个 C# WebApi 应用程序。我使用 Visual Studio 使用此配置对其进行调试。

server configuration

我安装了 nuget Microsoft.AspNet.WebApi.Cors 并在文件 WebApiConfig.cs 中我有以下代码:

    public static class WebApiConfig
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public static void Register(HttpConfiguration config)
{
config.EnableCors();

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{language}/{method}/{id}",
defaults: new { method = RouteParameter.Optional, id = RouteParameter.Optional }

);
}
}

在我的所有后端方法中,我都有这个装饰器

    [EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthenticationController : ApiController
{
[Route("api/Authentication/{language}/GuestUser")]
[HttpPost]
[Attributes.SiteParameter_Check]
public IHttpActionResult GuestAuthorization(string language)
{
//code with breakpoints never raised.
}

在 Angular 项目中我有这篇文章

    function guest(){
url = `${environment.baseUrlApi}Authentication/IT/GuestUser`;
return this.http.post(url, {}, )
.toPromise()
.then(response => {
//other code
})
}

我收到此错误

Access to XMLHttpRequest at 'http://localhost:8082/backend/api/Authentication/IT/GuestUser' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

已经尝试将文件 proxy.conf.json 放入 Angular 项目的 src 文件夹中

{
{
"/api/*": {
"target": "http://localhost:8082/backend/api",
"secure": false,
"logLevel": "debug"
}
}

我将这一行放入文件 angular.json

     "serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "frontend:build",
"proxyConfig": "src/proxy.conf.json"
},

这是我的网络配置

    <?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<configSections>

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>

<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" executionTimeout="1200" maxRequestLength="1048576" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
</system.web>

<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>

<validation validateIntegratedModeConfiguration="false" />
<directoryBrowse enabled="true" />

<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647" />
</webServices>
</scripting>
</system.web.extensions>

<connectionStrings>
---all my connection strings
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>

</configuration>

我缺少什么?

非常感谢

最佳答案

Put this in WebApiConfig

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");// origins, headers, methods
config.EnableCors(cors);

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

请添加这些引用文献

使用Newtonsoft.Json.Serialization;

使用 System.Web.Http.Cors;

注意:仅更改 WebApiConfig 就足够了。无需任何配置

关于来自原点的 Angular 和 WebApi Cors 请求已被 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68236912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com