I suspect this is a very simple solution. I have created a brand new ASP.NET Core 6 project (in VS 2022) with React. The default project has a WeatherForecast
component. I have duplicated this component and attempted to create a new controller. Unfortunately it is only returning the fallback Index.html
.
Here is the code:
// React
async getSitemapData() {
//axios.get("Sitemap")
// .then(resp => {
// console.log(resp.data);
// this.setState({ sitemap: resp.data, loading: false });
// });
const response = await fetch('sitemap');
const data = await response.json(); //execution does not reach this line
console.log(data);
this.setState({ sitemap: data, loading: false });
}
//program.cs controller mapping
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
//SitemapController.cs
using Microsoft.AspNetCore.Mvc;
namespace Intranet.Controllers
{
[ApiController]
[Route("[controller]")]
//public class DataController : ControllerBase
//Edit updated controller name
public class SitemapController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
try
{
// Read the data.json file and return its contents as JSON
var path = Path.Combine(Directory.GetCurrentDirectory(), "/App_Data/sitemap.json");
var data = System.IO.File.ReadAllText(path);
return new JsonResult(data);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
}
}
And for reference here is the functioning WeatherForecastController
:
//WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
namespace Intranet.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Aside from the returned datatype (the sitemap reads a JSON file and returns the contents rather than an array. The JSON is valid as I have used it in another site which is being revamped now), everything I can see tells me it should work. Thank you.
2
Answers
Most likely, your code is not finding the JSON file you’re trying read. A likely culprit
Directory.GetCurrentDirectory
which might not be what you expect at runtime.For serving static files, the ASP.NET documentation has the following suggestion:
You need to add the URL into
setupProxy.js
firstlyThen you can use
const response = await fetch('sitemap');
to hit theSitemapController
endpoint.