Tuesday, May 31, 2016

Web API to return JSON instead of XML

Web API to return JSON instead of XML

Concert crowd

Out of the box Web API generates XML as a result however if there is need for JSON as response than a little change may help you as given below:


Kinly open WebApiConfig.cs file add the following code segment depicted below in red:

public static void Register(HttpConfiguration config)
      {
          config.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector((config)));
                    
          config.Routes.MapHttpRoute(
              name: "Version1",
              routeTemplate: "api/v1/{controller}/{action}/{id}",
              defaults: new { controller = "Employees", Action = "FetchEmployeeById", id = RouteParameter.Optional }
          );

//To produce JSON format add this line of code

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(newMediaTypeHeaderValue("text/html"));

}

Hope it will help you.

Learn more about MVC and WebApi :

http://www.dotnetpiper.com/search/label/MVC

http://www.dotnetpiper.com/search/label/WCF%20and%20WebAPI

Wednesday, May 18, 2016

[Error-Messages%255B2%255D.png]

"Attempt by method 'System.Web.Http.GlobalConfiguration..cctor()' to access field 'System.Web.Http.GlobalConfiguration.CS$<>9__CachedAnonymousMethodDelegate2' failed."

Hi Amigo’s

Today when i was working on WebAPi and enabling CORS for WebAPI ,i confronted an error which took time to resolve and finally resolved.

To mitigate such issue you should have to install one of the possible insatalltion using NuGet Package Manager console.

Go to NuGet Package Manager console and select Default Project in which you would like to get this feature enabled and run the following command as shown below.

Install-Package Microsoft.AspNet.WebApi –IncludePrerelease

image

I will resolve an error and will help to proceed further with you business logic.

To know more MVC and WebApi Kindly go through with these links

MVC Articles & WCF and WebAPI

Thanks