Unable to access Web API from other web apps

Cloud Developer 1 Reputation point
2021-09-10T20:02:17.51+00:00

I have a webAPI (.NET CORE), that I'm able to access and see the data when I use the browser, however, when I try to access the web api from my React App, it's unable to it. When I go to Dev tools for the React App and click on Network, I can see the data from the WebAPI. I tried to connect to it from an .NET CORE MVC App an get ERR_EMPTY_RESPONSE.

Do I need to do something to the WebAPI to allow other apps to access it?

I have this in the StartUp.cs file in the WebAPI Project: Am I missing something?

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(c =>
           {
               c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod()
               .AllowAnyHeader());
           });

            services.AddControllersWithViews()
                 .AddNewtonsoftJson(options =>
                 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft
                 .Json.ReferenceLoopHandling.Ignore)
                 .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
                 = new DefaultContractResolver());

            services.AddControllersWithViews();
            services.AddHttpContextAccessor();


            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,203 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,926 Reputation points
    2021-09-11T15:17:28.457+00:00

    To access from JavaScript, if the webapi is not the same site hosting the react page, you need to implement CORS on your webapi.

    Does the browser network tool show an error? What is the response content? What is the the response content type?

    0 comments No comments

  2. Cloud Developer 1 Reputation point
    2021-09-13T11:13:45.577+00:00

    I have them as two separate projects. I'm running them both on my local pc during development. When I hit F12, I can see the data being returned from the WebAPI. This is what the Startup.cs file looks like in the API: It does have the CORS information in there, do I need to add more?

     public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(c =>
               {
                   c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod()
                   .AllowAnyHeader());
               });
    
                services.AddControllersWithViews()
                     .AddNewtonsoftJson(options =>
                     options.SerializerSettings.ReferenceLoopHandling = Newtonsoft
                     .Json.ReferenceLoopHandling.Ignore)
                     .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
                     = new DefaultContractResolver());
    
    
                services.AddHttpContextAccessor();
    
    
                services.AddControllers();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    
    
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseHttpsRedirection();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
    

    In my React APP. it's failing here: dealer.map is not a function message but again, if I hit F12 in the React App. I go to Network, I can see the data in the JSON response.

     <tbody>
                           {dealer.map(ad=>
                            <tr key={ad.dealerId}>
                                <td>{ad.dealerName}</td> 
                            </tr>)}
                        </tbody>
    
    0 comments No comments

  3. Bruce (SqlWork.com) 56,926 Reputation points
    2021-09-13T14:46:43.187+00:00

    The error means dealer is not an array.

    0 comments No comments

  4. Cloud Developer 1 Reputation point
    2021-09-13T15:30:24.033+00:00

    The WebAPI is returning data, I can see the data when I run F12 --> Network. I can see the call to the API and the data returned. such as:

    The WebAPI Output:

    {
        "data": [{
                "dealerId": 1,
                "dealerName": "Smith's Ford"
            }, {
                "dealerId": 2,
                "dealerName": "O'Reily's Cheverlot"
            }, {
                "dealerId": 3,
                "dealerName": "Main Line Nissan"
            }
        ]
    }