简体   繁体   中英

Angular front-end getting error when calling api on c# back-end

I have an Angular front-end and ac# webAPI back-end. The Angular front-end can retrieve data from other urls (eg http://reqres.in/api/users and json-server --watch db.json). The c# webAPI successfully returns data to api calls (entered in browser and sent from Postman (Get, http://localhost:49566/api/people )). When the front-end calls the back-end, gets the following: HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). (XHR)OPTIONS - http://localhost:49566/people

Any suggestions on what the problem is, or whether it is on the front-end or the back-end?

I have reviewed several Angular httpclient examples; but continue to experience the same thing--works with other urls; but not with my c# webAPI's url.

I have tried adding a post option; but that did not resolve it.

C# code:

        public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

Angular data service code:

  people: object;

  constructor(private http: HttpClient) { }

    searchClick(searchString: string) {
    return console.log('clicked ' + searchString);
  }

  getPeople() {
    const httpOptions = {
      headers: new HttpHeaders({
          'Access-Control-Allow-Origin': 'http://localhost:4200/',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': '*',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      })
    };
    return this.http.get('http://localhost:49566/api/People', httpOptions )  
}
}

What I need is for the front-end to successfully retrieve data from the back-end; so I can display it.

Change

   return this.http.get('http://localhost:49566/api/People', httpOptions )

to

   return this.http.get('http://localhost:49566/api/people', httpOptions )

the URL is case-sensitive.

Good luck!

The issue is related to CORS (on server-side) and method signature on server side.

First of all, enable CORS in your API code (C#). Please search MSDN for appropriate namespaces/dlls (eg System.Web.Cors ) needed.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

In API controller-derived class (eg), please do this to ensure the CORS is allowed. * means all URLs are allowed. Change as per your client (Angular app uri) needs.

/// <summary>
    /// Provides API for Order entity.
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class OrderController : ApiController
    {

In CORS, a pre-flight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. It is sent before sending a GET or POST .

Coming back to API code, in web.config , please ensure you have the following:

<system.webServer>
  <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>

<remove name="OPTIONSVerbHandler" /> ensures that IIS doesn't intercept OPTIONS requests.

Also in web.config , do the following. This ensures GET , POST and OPTIONS methods are allowed.

<httpProtocol>
      <customHeaders>            
        <!--...omitted for brevity-->

        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
      </customHeaders>

Finally:

[HttpGet]
public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

There's no need to do anything about CORS in client-side code in Angular. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM