web api json formatter in action return

Jak
Jak
908 Points
132 Posts

Hi,

I have added new project of web api. I have added following code in apiconfig for json formate:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
namespace example_API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit https://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: https://www.asp.net/web-api
//config.EnableSystemDiagnosticsTracing();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
}

 

But I want to this formatter in action wise in api controller.

Views: 9811
Total Answered: 1
Total Marked As Answer: 0
Posted On: 06-Oct-2015 00:08

Share:   fb twitter linkedin
Answers
Brian
Brian
2376 Points
13 Posts
         

Hi Jak,

You can return json format by using jsonformatter in action as:

public HttpResponseMessage GetJson()
{
var formatter = new JsonMediaTypeFormatter();
formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
return Request.CreateResponse(HttpStatusCode.OK, new{foo:"foomessage"}, formatter);
}

 

Posted On: 06-Oct-2015 04:46
 Log In to Chat