0

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 1

1

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

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

1 Comment

Thank you very much helped me alot

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.