How to setup wep api to only return json and enable Cors: (web api v2)

In WebApiConfig.cs file from App_Start folder and add the following code in the Register method –

config.EnableCors(); //if cross origin requests should be enabled
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);

This code does the following:

1. Converts names of properties to camel case while serializing the objects to JSON

2. Removes XML formatter from Web API’s formatters to make sure JSON data is returned on each request

Use this code to easily return json formatted response from api controller:

var employees= EmployeesRepository.GetAllEmployees();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return response;

Example code for setting up controller and action with cors:

[EnableCors(origins: "http://localhost:55058", headers: "*", methods: "*")]
public classPTEmployeesController : ApiController
{

// GET api/ptemployees
[Route("api/ptemployees")]
public HttpResponseMessage Get()
{
var employees= EmployeesRepository.GetAllEmployees();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return response;
}

...
}

From http://www.dotnetcurry.com/aspnet/1063/create-rest-service-using-aspnet-webapi

Leave a Reply