【发布时间】:2021-09-15 02:24:19
【问题描述】:
我有一个角度应用程序 (角度版本 角 CLI:8.3.26 节点:10.13.0 操作系统:win32 x64 角度:8.2.14)
在 environment.ts 中,我有后端的链接
export const environment = {
baseUrlNG: 'http://localhost:4200/',
baseUrlApi: 'http://localhost:8082/backend/api/'
}
后端是一个 C# WebApi 应用程序。 我使用此配置使用 Visual Studio 对其进行调试。
我安装了 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>
我错过了什么?
非常感谢
【问题讨论】:
-
我的后端是 ASP.NET WebApi 而不是 .NET Core
-
我之前在
[EnableCors]属性中遇到过methods: "*"的问题。您是否尝试过明确说明允许的方法?methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS"。此外,您只需要使用[EnableCors]来装饰控制器/操作,而不是 config 方法本身。 -
这并没有解决我的问题。我不知道如何设置赏金,因为我没有解决我的问题。
标签: angular asp.net-web-api cors