skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Can you try adding this to your program.cs file:

    app.UseAuthentication();
    app.UseAuthorization();
    

    Note that it has to be in that order.

    Login or Signup to reply.
  3. 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".

    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:

        [Route("[controller]")]
        [ApiController]
        public class DataController : ControllerBase
        {
            [HttpGet]
            [Route("alldata")]
            public IActionResult GetData()
           {
                var data = new { key1 = "test1", key2 = "test2" };
                return Ok(data);
            }
        
        }
    

    Program.cs file:

    In the program.cs file I have configured the CORS setting:

    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowOrigin",
            builder => builder.WithOrigins("YourReactEndpoint")
                              .AllowAnyHeader()
                              .AllowAnyMethod());
    });
    
    var app = builder.Build();
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    app.UseCors("AllowOrigin");
    app.MapControllers();
    
    app.Run();
    

    React Testing Code:

    I have used below approach in react for quick test:

    import React, { useEffect, useState } from 'react';
    
    export function App(props) {
      const [data, setData] = useState(null);
      const [error, setError] = useState(null);
    
      useEffect(() => {
      const fetchData = async () => {
        try {
          const response = await fetch('https://localhost:7299/Data/alldata');
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          const result = await response.json();
          console.log(result);
          setData(result);
        } catch (error) {
          setError(error);
        }
      };
    
      fetchData();
    }, []);
    
      return (
        <div className='App'>
         
        </div>
      );
    }
    

    Output:

    enter image description here

    enter image description here

    Note: Please refer to this example in case of your reference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search