ASP.NET Core MVC & ASP.NET Core Web API in same project

Jerry Lipan 916 Reputation points
2021-10-29T03:19:19.48+00:00

Currently, this is my UseEndpoints

  app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Account}/{action=Login}/{id?}");

            });

As a result, my ASP.NET Core MVC is running perfectly

Then, I'm adding Web API into this existing project. Here the code,

namespace TafaService.Controllers
{   
    [ApiController]
    [Route("api/[controller]")]
    public class TafaProjectsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly ProjectRepository _repository;

        public TafaProjectsController(ApplicationDbContext context, ProjectRepository repository)
        {
            _context = context;
            this._repository = repository ?? throw new ArgumentNullException(nameof(repository));



        }


  [HttpGet]
        public IEnumerable<serviceProject> GetProjects()
        {

            return _context.serviceProjects
              .FromSqlRaw("[dbo].[apiProjects_GetProjects]").ToList();
        }


}


}

The Web API cannot invoke

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-e7e38ff1d044ae45a30e27401c990a66-3c482c3f5784344a-00","errors":{"id":["The value 'GetProjects' is not valid."]}}

Looks like, my Startup.cs having a problem. I don't have any idea to modify

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,077 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 31,756 Reputation points Microsoft Vendor
    2021-11-01T05:52:47.677+00:00

    Hi @Jerry Lipan ,

    The Web API cannot invoke

    {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-e7e38ff1d044ae45a30e27401c990a66-3c482c3f5784344a-00","errors":{"id":["The value 'GetProjects' is not valid."]}}

    The issue relates the request URL. Based on your code, you should remove the GetProjects from the request URL. After modifying, the URL should like this: https://localhost:44310/api/TafaProjects

    You can refer this screenshot:

    145343-image.png

    If you want to set a method name in the quest URL, you can add the name in the HttpGet verb. Like this:

    145308-image.png

    More detail information, you can check Routing to controller actions in ASP.NET Core.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Jerry Lipan 916 Reputation points
    2021-11-01T05:06:01.31+00:00

    Hi @AgaveJoe

    My ASP.NET Core MVC work fine. This is Startup.cs

    145381-01.png

    When running,

    145391-02.png

    145362-03.png

    Next, I adding Web API into existing ASP.NET Core MVC like this,

    Model: serviceProject.cs

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Threading.Tasks;  
    using System.ComponentModel.DataAnnotations;  
      
    namespace HelpDesk.ViewModel  
    {  
        public class serviceProject  
        {  
            [Key]  
            public string Id { get; set; }  
      
            public string ProjectCode { get; set; }  
      
            public string ProjectName { get; set; }  
             
            public string ClientId { get; set; }  
      
            public string ClientName { get; set; }  
      
      
        }  
    }  
    

    DB Context: ApplicationDbContext.cs

    using HelpDesk.Model;  
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
    using Microsoft.EntityFrameworkCore;  
    using HelpDesk.Models;  
    using HelpDesk.ViewModel;  
      
    namespace HelpDesk.Data  
    {  
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  
        {  
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)  
                : base(options)  
            {  
      
      
            }  
      
            //start API  
            public DbSet<serviceProject> serviceProjects { get; set; }  
      
            //end API  
    

    Stored Procedure: apiProjects_GetProjects
    145327-04.png

    145392-05.png

    API Controller: TafaProjectsController

    using Microsoft.AspNetCore.Mvc;  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using Microsoft.EntityFrameworkCore;  
    using HelpDesk.ViewModel;  
    using HelpDesk.Data;  
      
    // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
      
      
    namespace TafaService.Controllers  
    {  
          
        [ApiController]  
        [Route("api/[controller]")]  
        public class TafaProjectsController : ControllerBase  
        {  
            private readonly ApplicationDbContext _context;  
            private readonly ProjectRepository _repository;  
      
            public TafaProjectsController(ApplicationDbContext context, ProjectRepository repository)  
            {  
                _context = context;  
                this._repository = repository ?? throw new ArgumentNullException(nameof(repository));  
      
                 
      
            }  
        
            [HttpGet]  
            public IEnumerable<serviceProject> GetProjects()  
            {  
                 
                return _context.serviceProjects  
                  .FromSqlRaw("[dbo].[apiProjects_GetProjects]").ToList();  
            }  
      
       
      
      
      
      
        }  
    }  
    

    This is Postman,
    145401-06.png

    In Debugging, looks like the code is not invoke

    145364-07.png

    Please help

    0 comments No comments

  2. Jerry Lipan 916 Reputation points
    2021-11-01T10:49:27.637+00:00

    Hi @Zhi Lv - MSFT

    It's working. Million thanks

    0 comments No comments