4

I am trying to make n-tier application where web api is kept on a different class library. I made a TestController controller class in a different class library and my code goes like this

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace PkrUni.SMS.Api
{
    [ApiController]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class TestController : ControllerBase
    {
        public IEnumerable<string> Get()
        {
            return new string[] { "Chris", "Hadfield" };
        }
    }
}

Now my question is how can I access this web api on my main project. I had already added a reference to that class library on main project but it doesn't working. My api is not working. 404 Page Not Found error shows up while trying to access the api. This is my project structure.

enter image description here

What am I doing wrong please help me.

11
  • Perhaps this. The controllers are referenced, but the app doesn't know to look for controllers in any assembly but its own. Commented Apr 29, 2019 at 16:22
  • 1
    Why did you put the controllers in a separate project anyways? That's not really required for an N-Tier app. Commented Apr 29, 2019 at 16:26
  • @mason Api controller are only on different project but mvc controller are in main project. Is it bad practice to have api controller in different class Commented Apr 29, 2019 at 16:27
  • It's not necessarily bad. But what advantage does it give you? I can't think of any. And if it's making it harder to build/run your app....I think you should think of the positives and negatives of your approach and decide whether it's worth it. Commented Apr 29, 2019 at 16:29
  • @mason Can you tell me how to call an web api without exposing it on network tab of browser. Commented Apr 29, 2019 at 16:55

1 Answer 1

2

Try to install Microsoft.AspNetCore.Mvc package in the razor class library. And in startup.cs use:

services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("PkrUni.SMS.Area.Api")));

Refer to here.

I test your scenario by creating a asp.net core2.2 MVC project and razor class library without any problem. Below is my structure:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.