【问题标题】:How to display text received from a web api in angular 2如何以角度 2 显示从 web api 接收的文本
【发布时间】:2017-02-13 03:29:03
【问题描述】:

我有一个返回字符串的 Asp.Net Core web api 方法。

   [Route("GetString")]
        public string GetString()
        {
            return "String from <b> Web </b> API";
        }

该 URL 在浏览器中可以正常工作,但是,当我从 Angular 2 应用程序运行它时

getDialog(){  
      this.result = this.http.get(this._stringUrl1).forEach((response) => response.text); 
      console.log(this.result); 
}

我收到以下错误消息:

XMLHttpRequest cannot load http://localhost:49596/Content/GetString. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

如果我调用返回 HttpResponseMessage 的 web api 方法,我会得到相同的响应。

 [Route("GetHttpResponseMessage")]
        public HttpResponseMessage GetString2()
        {
            var response = new HttpResponseMessage();
            response.Content = new StringContent("HttpResponseMessage from Web API 2", Encoding.UTF8, "Text/txt");
            return response;

        }

这是我的第一个 Angular 应用程序,所以我不确定我的 angular2 代码是否正确。任何帮助表示赞赏。

【问题讨论】:

  • 这不是你的 Angular 代码的问题;你需要在 API 端实现 CORS 处理。

标签: asp.net angular cors


【解决方案1】:

在asp.net web api(4.5)中,我发现你必须在两个地方添加权限: 1)启动时(webapiconfig.cs)

var cors = new EnableCorsAttribute(
                origins: "*",
                headers: "*",
                methods: "*");
config.EnableCors(cors);    

2) 在控制器级别 (pocoController.cs)

namespace BiGPOCO.API.Controllers
{
    [EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
    public class PocoController : ApiController
    {}
}

【讨论】:

    【解决方案2】:

    当您的客户端和服务器不在同一个域上运行时,通常会发生这种情况。

    您可以在 API 服务器上启用 CORS,因为您使用的是 C#,您可以在 web.config 中执行此操作仅用于开发。其中 3000 是您的客户端端口

    <customHeaders> <add name="Access-Control-Allow-Origin" value="http://localhost:3000" /> </customHeaders>

    或者有一个谷歌浏览器插件也可以实现这一点。 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en

    您可以在闲暇时轻松地打开和关闭此功能。还有其他方法以及修改您的请求标头等...

    这些更简单。

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 1970-01-01
      • 2017-05-19
      • 2019-05-26
      • 1970-01-01
      • 2020-06-29
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多