简体   繁体   中英

Add existing Web Api project to existing Mvc project

I have two projects in my solution, a mvc project and a web api project. What is the best way to go about utilizing the web api project within the mvc application?

Options that I have come up with so far:

  • Deploy both projects and use a helper class to interact with the api (javascript or server side)
  • Add reference to web api project which adds api functionality to mvc project (not sure how to integrate api project into mvc project correctly, how would I do this?)

If there is a better alternative please share.

In the folder Controllers you have files like this:

namespace BeerDev.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home";

            return View();
        }
    }
}

And create another folder called ControllersApi with files like this:

namespace BeerDev.ControllersApi
{
    public class HomeController : ApiController
    {
        public IHttpActionResult Get()
        {
            string beers;
            using (StreamReader sr = new StreamReader(HostingEnvironment.MapPath("~/mockData/beerFront.json")))
            {
                beers = sr.ReadToEnd();
            }

            if (string.IsNullOrEmpty(beers))
            {
                return NotFound();
            }
            return Ok(beers);
        }
    }
}

In the Web Api project there is a specialized kind of controller, but still a controller.

You can refer to this webAp2_example .

If ASP.Net MVC application is the only one that consumes Web API, it is make sense to have them both inside a single project.

In my scenario, I have SPA using Angular, so I keep MVC and Web API controllers in separate folders inside Controller folder.

The main advantage is that I can share models and class libraries. In addition, I do not have to worry about CORS.

在此处输入图片说明

API Controller

Notice the RoutePrefix .

namespace MyApp.Web.Controllers.API
{
    [RoutePrefix("api/users")]
    public class UsersApiController : ApiController
    {
    }
}

MVC Controller

namespace MyApp.Web.Controllers.MVC
{
    public class UsersController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

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