Good day together,
I try to trigger a ASP Controller from React. I tested many different things.But nothing works.
Sometimes I get the message in browser that routes does not exist (I try many routes) or "No routes matched location "/DataController/alldata". The last time I get the message "Enable to verify the first certificate".(From Postman)
Please help me. I sit on this Problem already to long 😉
Merry Christmas and go happy new year.
The current code:
ASP Controller
[Authorize]
[ApiController]
[Route("[controller]")]
public class DataController : Controller {
...
[HttpGet]
[Route("alldata")]
public IActionResult GetData(){
var data = new {key1="test1", key2="test2"};
return Ok(data)
}
React Code (fetch)
export const GetDataset = function () {
const fetchData = async() => {
try {
const result = await fetch('https://localhost:port/DataController/alldata')
const jTest = await result.json();
}catch(error){
.....
}
}
fetchData()
}
React Component Call
componentDidMount() {
GetDataset();
}
3
Answers
When you use
[controller]
in the route, that means the name of the controller class minus the word Controller.So your URL should be something like:
https://localhost:port/Data/alldata
.Can you try adding this to your program.cs file:
Note that it has to be in that order.
Well, based on your shared code snippet and description, I have tried to reproduce your issue, and was I able to hit the controller endpoint and got the response accordingly.
Altough, your code seems alright and I have just omitted the
[Authorize]
because I don’t need that in order to execute my testing scenario. Its working accordingly.Here is the steps I did, for calling he API from the react endpoint:
Controller:
Almost same as yours:
Program.cs file:
In the program.cs file I have configured the CORS setting:
React Testing Code:
I have used below approach in react for quick test:
Output:
Note: Please refer to this example in case of your reference.