Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object on ASP.NET Web API?

This is my Web API and it works fine, I mean when i enter this URL on my browser:

http://localhost:18207/api/values/GetMyClass

I retrieve this result:

<MyClass>
<A>a</A>
<b>b</b>
</MyClass>

My codes:

public class MyClass
{
    public MyClass()
    {
        this.A = "a";
        this.b = "b";
    }
    public string A { get; set; }
    public string b { get; set; }
}


public class ValuesController : ApiController
{
    public MyClass GetMyClass()
    {
        return new MyClass();
    }
}

I have another console application to use my Web API and want to know, How can i have a complex or object type of MyClass?

Codes on my Console are below but it returns string type

 static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        MainAsync(args, cts.Token).Wait();
    }

    static async Task MainAsync(string[] args, CancellationToken token)
    {
        string baseAddress = "http://localhost:18207/api/values/GetMyClass";

        using (var httpClient = new HttpClient())
        {
            string response = await httpClient.GetStringAsync(baseAddress);
        }
    }
like image 219
motevalizadeh Avatar asked Dec 16 '15 16:12

motevalizadeh


People also ask

How do I pass a class object as parameter in Web API?

Show activity on this post. MakeUser method in the User controller for creating a username and password. UserParameter class for sending the parameters as an object. RunAsync method in console client.


1 Answers

Your response is probably coming to your console application as JSON (the reason your browser receives it as XML is because of different Accept headers, you can learn about that if you look at Content Negotiation). So what you need to do is parse the JSON and have it deserialize it into your object. There's quite a few libraries that can do that for you.

First make sure that your MyClass is defined in a Class Library project that both your Web API project and your Console project are referencing. This allows us to reuse the class definition without needing to have a separate copy in both projects.

Next, you need a JSON parsing library. There's one built into .NET, but there's a 3rd party one called Json.NET that is the gold standard. My answer will use that one since I'm more familiar with it. Install the Newtonsoft.Json package into your console app.

Then, change your console app as follows:

using Newtonsoft.Json; // at the top of your file

static void Main(string[] args)
{
    var cts = new CancellationTokenSource();
    MainAsync(args, cts.Token).Wait();
}

static async Task MainAsync(string[] args, CancellationToken token)
{
    string baseAddress = "http://localhost:18207/api/values/GetMyClass";

    using (var httpClient = new HttpClient())
    {
        string json = await httpClient.GetStringAsync(baseAddress);
        MyClass instance = JsonConvert.DeserializeObject<MyClass>(json);
    }
}

The JsonConvert class handles serializing and deserializing the JSON. When deserializing, we just tell is which class to deserialize to and it will attempt to convert the JSON to an instance of that class and return it.

like image 133
mason Avatar answered Oct 02 '22 07:10

mason