使用 Angular 的 http 请求 WebApi 失败

Posted

技术标签:

【中文标题】使用 Angular 的 http 请求 WebApi 失败【英文标题】:Failed http request WebApi using Angular 【发布时间】:2021-02-28 03:45:30 【问题描述】:

我正在尝试从 Angular 连接在 .net 中创建的服务,但 CORS 出现错误,我已经查找了许多链接,但没有一个对我有帮助,因为大多数解决方案都是针对 .NET CORE 而我使用的是标准.net .

从角度调用:

 return this.http.post('http://localhost:50112/api/auth', userdata).toPromise();

API:

public class AuthController : ApiController

    public async Task<IHttpActionResult> Auth(User userdata)
    
        var result = await bllUser.auth(userdata);
        return Ok(result);
    

这个错误:

Access to XMLHttpRequest at 'http://localhost:50461/api/auth' 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.

我也尝试在我的 webapiconfig 文件中添加 config.EnableCors 语句,但它告诉我该语句不存在

非常感谢您的帮助,没有任何解决方案对我有用

【问题讨论】:

【参考方案1】:

使用启用 cors

将 CORS 安装到 API 项目“Install-Package Microsoft.Asp.Net.WebApi.Cors”中。 并更改您的注册方法

public static void Register(HttpConfiguration config)

    var cors = new EnableCorsAttribute("www.example.com", "*", "*");
    config.EnableCors(cors);
    // ...

【讨论】:

以上是关于使用 Angular 的 http 请求 WebApi 失败的主要内容,如果未能解决你的问题,请参考以下文章

angular 中使用 axios 发起 http 请求

Node + Angular:使用 HTTP 请求下载文件

具有基本身份验证的 Angular 7 HTTP 请求 [关闭]

无法使用 Angular 2 rc5 发出 http 请求

如何使用http在angular2中发出请求?

angular 中的 http 请求