user11196706
user11196706

Reputation:

MVC Routing in .NET Core React project isn't picking up my Controller

I am learning how to create React applications with ASP.NET Core. As a newbie I am starting at the very beginning and trying to get "Hello World" displayed on the home page. I have used Visual Studio's default React.js project template to get me started. The routes are set to default. Here are my files:

Home.js:

import React, { Component } from 'react';

export class Home extends Component {

    constructor(props) {
        super(props);
        this.state = { message: "" };

        fetch('api/Home/Message')
          .then(response => response.json())
          .then(data => {
          this.setState({ message: data });
        });

    }

  render () {
      return (

            <h1>{this.state.message}</h1>

    );
  }
}

HomeController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;


namespace TestingReactDotNet.Controllers
{
[Route("api/[controller]")]   
public class HomeController :  Controller
    {
        [HttpGet]
        public async Task<IActionResult> Message()
        {
            var response = "Hello World";
            return Ok(response);
        }
    }
}

The problem is that the HTTP response that is being parsed to Json isn't the correct one. I have console.logged it out in order to try to debug, and it appears that response.json()) is retrieving all of the text in the default public/index.html file that comes with the template application. Does anyone have any idea why this is?

Apologies if I am missing something super obvious - I use a Mac, so the file structure and Visual Studio IDE are quite different and I have struggled to understand quite a few of the tutorials/answers already out there.

Upvotes: 3

Views: 2741

Answers (3)

Jorch
Jorch

Reputation: 21

I solved the problem by adding a context line in setupProxy.js You can locate it at

ClientApp -> src -> setupProxy.js

You must add the name of controller you want to use in the array context list.

Upvotes: 2

Michael Domashchenko
Michael Domashchenko

Reputation: 1480

Class Controller is for MVC which does generate full web pages.

For Web API you need to extend ControllerBase. And you should just return your value/object straight:

[Route("api/[controller]")]
[ApiController]
public class HomeController :  ControllerBase
{
    [HttpGet, Route("message")]
    public async Task<string> Message()
    {
        var response = "Hello World";
        return response;
    }
}

Upvotes: 0

Noremac
Noremac

Reputation: 594

To hit your Message() function you must make a HttpGet to 'api/Home' not 'api/Home/Message'.

If you want your endpoint to be 'api/Home/Message' then you must specify the route for the Message() function like so:

// api/Home/Message
[HttpGet, Route("Message")]
public async Task<IActionResult> Message()

Upvotes: 1

Related Questions