简体   繁体   中英

How to call controller methods from react

I am trying to learn React with ASP.NET Core 3.0 and I have some issues with calling Controllers' methods. If controller has single method like Get() everything is fine. But if it has more than one, then it turns out as error. Something like Multiple Endpoint conflict. I can't understand and can't find any information about this.

I call methods with code like this:

await FetchData(){
    const response = await fetch('api/article/makenewpost/?id=');
    const data = await response.json();
    this.setState({data:data});
}
async fetchData() {
        const response = await fetch('api/article/getarticles/?id=' + this.props.id);
        const data = await response.json();
        this.setState({ blocktitle: this.props.blocktitle, data: data, id: this.props.id });
    }

As temporary solution I made Get method in controller with switch statement, but it looks very bad to me.

public IActionResult Get(int? id, string method){
    switch (method)
    {
        case "GetArticles":
        {...}
        case "MakeNewPost":
        {...}
    }
}

UPDATE: Tried saidutt's solution. There is no conflict anymore, but in response I have something like manifest file, so it's error as I read. Why I can't get correct response? I just separated my methods from single switch method.

[Route("api/[controller]")]
public class ArticleController : Controller
{
    private readonly DzikanContext _context;
    public ArticleController(DzikanContext context)
    {
        _context = context;
    }
    // GET: api/<controller>        

    [Route("api/[controller]/getarticles")]        
    public IActionResult GetArticles(int id)
    {


        var titles = _context.Post.Where(p => p.TypeId == id).Select(p => p);
        var filtered = titles.Skip(Math.Max(0, titles.Count() - 3)).ToList();


        Dictionary<int, string> icons = new Dictionary<int, string>
        {
            {1, "someUrl" },
            {2, "someUrl2"},
            {3, "someUrl3" }

        };

        List<PostsPayload> articles = new List<PostsPayload>();

        foreach (var title in filtered)
        {
            articles.Add(new PostsPayload
            {
                IconUrl = icons[title.ResourceId],
                ArticleBody = title.Title
            });
        }
        return Json(articles.ToArray());
    }

    [Route("api/[controller]/makenewpost")]
    public IActionResult MakeNewPost(int id)
    {
        var articles = _context.Post.Where(p => p.Id == id).Select(p => p);
        var title = articles.Select(p => p.Title).First();
        var body = articles.Select(p => p.Body).First();
        List<Post> posts = new List<Post>{
               new Post
                {
                    Title = title,
                    Body = body
                }};
        return Json(posts.ToArray());
    }
}

As I said earlier, when I use single method with switch (nothing has been changed in methods when I separated them) it works fine.

Add Routes to individual endpoints in the controller.

[Route("api/posts/createnewpost")]
public IActionResult CreateNewPost(...) { /* your logic */ }
[Route("api/[controller]")]
[ApiController]
public class ArticleController : Controller
{
    private readonly DzikanContext _context;
    public ArticleController(DzikanContext context)
    {
        _context = context;
    }
    // GET: api/<controller>        

    [HttpGet]        
    public IActionResult GetArticles(int id)
    {


        var titles = _context.Post.Where(p => p.TypeId == id).Select(p => p);
        var filtered = titles.Skip(Math.Max(0, titles.Count() - 3)).ToList();


        Dictionary<int, string> icons = new Dictionary<int, string>
        {
            {1, "someUrl" },
            {2, "someUrl2"},
            {3, "someUrl3" }

        };

        List<PostsPayload> articles = new List<PostsPayload>();

        foreach (var title in filtered)
        {
            articles.Add(new PostsPayload
            {
                IconUrl = icons[title.ResourceId],
                ArticleBody = title.Title
            });
        }
        return Json(articles.ToArray());
    }
    // api/<controller>/makenewpost
    [HttpGet("makenewpost")]
    public IActionResult MakeNewPost(int id)
    {
        var articles = _context.Post.Where(p => p.Id == id).Select(p => p);
        var title = articles.Select(p => p.Title).First();
        var body = articles.Select(p => p.Body).First();
        List<Post> posts = new List<Post>{
               new Post
                {
                    Title = title,
                    Body = body
                }};
        return Json(posts.ToArray());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM