Reputation: 109
I have created an ASP.NET Web API which finds the sum of two integers using an addition function from a dll file. When i run the application (http://localhost:52241/api/dlladdition/9/6
) i get results as "15"
. The result i want is something like { "result" : 15}
(JSON format). How do i achieve that? The JSON codes that i have included in my codes does not seem to work.
Here are my codes:
Addition.cs
using ClassLibraryDll;
public class Addition
{
static int num1;
static int num2;
int sum = MathClass.Add(num1, num2);
}
DllAdditionController.cs
public class Temp
{
public int num1 { get; set; }
public int num2 { get; set; }
public int sum { get; set; }
}
public class DllAdditionController : ApiController
{
private Addition addition = new Addition();
public int GET(int num1, int num2)
{
int result = ClassLibraryDll.MathClass.Add(num1, num2);
string json = JsonConvert.SerializeObject(result);
return (json);
}
}
Someone please help me. Thank you so much in advance.
Upvotes: 0
Views: 2795
Reputation: 172380
my project manager insists for it to be in JSON format :/
It is valid JSON. Your project manager needs to read up on the current JSON specs.
If you want your result wrapped in an object with a result
property, you are free to define a class with a single property result
and return this class instead.
Upvotes: 1
Reputation: 194
You can set the response to by JSON by using the JSON Media-Type Formatter
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
If you like to restrict your Web API response to either JSON or XML only, you can call this from your Application_Start method, defined in Global.asax.
void ConfigureApi(HttpConfiguration config)
{
// Remove the JSON formatter
config.Formatters.Remove(config.Formatters.JsonFormatter);
// or
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
You may refer to https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization#removing-the-json-or-xml-formatter for more information.
Upvotes: 1