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:
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.
Notice the RoutePrefix .
namespace MyApp.Web.Controllers.API
{
[RoutePrefix("api/users")]
public class UsersApiController : ApiController
{
}
}
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.