Fixus
Fixus

Reputation: 4641

how can I send object from c# webapp to asp.net webapi

for 3 days i'm trying to send my object to my webapi. I just can't do it from c# :/

I was trying PostAsync method, i was trying to send json (but then I can't deserialize), i was trying to use JObject but can't do nothing with it. I just don't know how to do this.

I got rly simple method

    public string PostMethod(Location param)
    {
        var test = param;

        return test.name;
    }

how can I send Location object from c# so I won't get null in webapi ? Only thing i've achived is to send a simple type like 'string'. But none of my metrhods works with more complex objects.

Below Location object

public partial class Location
{
    public Location()
    {
        this.Category = new HashSet<Category>();
    }

    public int id { get; set; }
    public Nullable<System.DateTime> create_date { get; set; }
    public Nullable<System.DateTime> modify_date { get; set; }
    public Nullable<int> create_user_id { get; set; }
    public Nullable<int> modify_user_id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public Nullable<int> photo_id { get; set; }
    public string www { get; set; }
    public string count_data { get; set; }
    public string status { get; set; }
    public Nullable<double> latitude { get; set; }
    public Nullable<double> longitude { get; set; }
    public string city { get; set; }
    public string country { get; set; }
    public string zip { get; set; }
    public string telephone { get; set; }
    public string street { get; set; }

    public virtual AzureMedia AzureMedia { get; set; }
    public virtual Users Users { get; set; }
    public virtual Users Users1 { get; set; }
    public virtual ICollection<Category> Category { get; set; }
}

Upvotes: 2

Views: 1316

Answers (1)

Remy
Remy

Reputation: 12703

Did you install the newest Web API from NuGet? And you need the Json.NET too for this.

This should do the trick:

    Location loc = new Location( ..... );

    var jsonFormatter = new JsonMediaTypeFormatter();

    HttpContent content = new ObjectContent<Location>(loc , jsonFormatter);

    HttpResponseMessage responseMessage = client.PostAsync(uri, content).Result;

Upvotes: 4

Related Questions