J.D. J.D. - 2 months ago 37
ASP.NET (C#) Question

How to display text received from a web api in angular 2

I have an Asp.Net Core web api method that returns a string.

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


The URL works fine in a browser, however, when I run it from an angular 2 app

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


I get the following error message:

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.


I get the same response if I call a web api method that returns an HttpResponseMessage.

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

}


This is my first Angular app so I am not sure if my angular2 code is correct or not. Any help is appreciated.

mg3 mg3
Answer

in asp.net web api (4.5), i found out that you have to add the permission in two places: 1) at startup (webapiconfig.cs)

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

2) at the controller level (pocoController.cs)

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