【问题标题】:Failed http request WebApi using Angular使用 Angular 的 http 请求 WebApi 失败
【发布时间】: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 语句,但它告诉我该语句不存在

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

【问题讨论】:

    标签: c# .net api cors handle


    【解决方案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);
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 2014-11-19
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多