Radek Strugalski
Radek Strugalski

Reputation: 568

How to post complex object to Post method of the controller via HttpClient with headers?

The question has focus on providing headers with the request, so I presume only HttpClient.SendAsync() method is to be considered. Not PostAsync or PostAsJsonAsycn()

Here is the code I use to send a POST request:

var request = new HttpRequestMessage()
{
    RequestUri = new Uri(@"http://test/" + controllerUri),
    Method = HttpMethod.Post,
};

request.Headers.Add(_authHeader, c_authToken);
request.Content = new ObjectContent<RequestType>(content, new JsonMediaTypeFormatter());

var result = _client.SendAsync(request).Result;

I am constantly getting 500 error saying that Duration property on the serialized object is invalid, although in fact is it set in the object.

I tried StringContent with mediatype set to "application/json" but I got the same error.

The controller's post method has the following signature:

public HttpResponseMessage Post(MyContentObject content) { ... }

Exception is thrown before entering to the method.

Interestingly enough, when I commented out [Required] attribute from MyContentObject:

public class MyContentObject
{
    [Required]
    public int Duration { get; set; }

    public decimal SomePropA { get; set; }
    public bool SomePropB { get; set; }
}

it works and Duration property is set correctly as expected.

So maybe the question is why adding [Required] attribute in this case is making so much problems? There may be questions from you on why there is [Required] attribute added to an int property. My answer is I don't know who added it and for me it does not make sense, but if it does, please let me know.

Thanks

Upvotes: 2

Views: 1643

Answers (1)

Radek Strugalski
Radek Strugalski

Reputation: 568

I did more research on this. So I will start from the end. The [Required] annotation issue is covered in this thread: http://aspnetwebstack.codeplex.com/workitem/270

Basically built-in InvalidModelValidatorProvider checks models validation for nonsensical annotation like this above (value type properties have always a value) and throws an exception. The article above mentions also a workaround to avoid an exception to be thrown without changing the existing annotation.

The following code enables you to post an object serialized as JSON with headers attached:

// var RequestType content <- this is an input parameter. 

var request = new HttpRequestMessage()
{
    RequestUri = new Uri(@"http://test/" + yourControllerUri),
    Method = HttpMethod.Post,
};

request.Headers.Add("YourHeaderName", "YourHeaderValue");
request.Content = new ObjectContent<RequestType>(content, new JsonMediaTypeFormatter());

var result = _client.SendAsync(request).Result;

I hope somebody will find it useful.

Upvotes: 1

Related Questions