i want to create .net mvc project but i also want to add wep api within the same project, do will i need a controller for api and a controller for a normal .net mvc ? i have searched in google but i didn't find a helpful solution, any answer will definitely help me Thanks a lot.
1 Answer
Follow these steps:
1- Add webapiconfig.cs file in App_Start folder
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
2- In Global.ascs.cs file add the new line mentioned in the comment. Your Application_Start function should look like below.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);//new line for webapi
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
3- Now add a new apicontroller like below.
public class TestController : ApiController
{
public IHttpActionResult GetAll()
{
return Json("test");
}
}
4- Api url will be like "http://localhost:61012/api/Test/GetAll"
5- Don't forget to add this nuget package : Microsoft.AspNet.WebApi
1 Comment
Mohammed Z. Aljezawi
Thank you very much helped me alot