Wednesday, July 6, 2016

How to add Web API to an existing ASP.NET MVC Web Application

The steps I needed to perform were:
  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs (see code snippet below).
  3. Import namespace System.Web.Http in Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.
I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
App_Start\WebApiConfig.cs:
using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });


// To return objects in Json format (Not XML Format),
var appXmlType = configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

    }
}
Global.asax.cs:
using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Use TypeScript in SharePoint Hosted App

There is trick involved in making Visual Studio realize to compile TypeScript and generate javascript files, Following procedure will give you complete guidance how to complete the process.

1.      Create a new Sharepoint-hosted app.
a.      Right-click the project name and select Unload Project.
b.      Right-click the project name and select Edit <your project name>.csproj.
c.      Add these lines before the last closing <Project> tag. 

    <TypeScriptSourceMap>true</TypeScriptSourceMap>
  </PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" />

1.      Right-click the project name and select Reload Project.
2.      Now you will see the TypeScript tab in the project properties.


2.      Now you can add the TypeScript definitions. Right-click the project name and select Manage Nuget Packages. Search online for “sharePoint.Typescript.” Install thesharePoint.Typescript.DefinitelyTyped package.      

3.      Also search for “jquery.typescript” and install the jquery.Typescript.DefinitelyTyped package.

Now you are ready to work with Typescript and can create Typescript files.