FubarDevelopment / restsharp.portable

Some kind of a RestSharp port to PCL
BSD 2-Clause "Simplified" License
96 stars 33 forks source link

BSON causes POST to fail? Never reaches desired Web API endpoint #93

Closed dylinmaust closed 7 years ago

dylinmaust commented 7 years ago

I'm able to successfully execute a simple post using Swagger against my .NET Web API project:

{
  "application_version": "3.2",
  "device_type_id": 2,
  "allergens": [],
  "preferences": [],
  "demographics": []
}

However, attempting to send the same request via RestSharp portable library yields an HTTP 500 error. The request never reaches the desired endpoint. Sample code below.. Please note that the ConsumerDto seen below uses JsonProperty annotations to convert property names to snake case, e.g. ApplicationVersion to application_version.

var consumer = new ConsumerDto
{
    ApplicationVersion = "3.2",
    DeviceTypeId = 2,
    Allergens = new List<int>(),
    Demographics = new List<DemographicDto>(),
    Preferences = new List<int>()
};

var request = new RestRequest("api/consumer", Method.POST);
request.AddJsonBody(consumer);
await _client.Execute<int>(request);

I assume this is because the ISerializer interface returns a byte[] (from what I understand, binary JSON or BSON) rather than the JSON representation of the object. I've tried adding config.Formatters.Add(new BsonMediaTypeFormatter()); to my Web API project, but it made no difference.

What am I doing incorrectly? Thanks

fubar-coder commented 7 years ago

RestSharp.Portable doesn't support BSON. The byte[] is the byte sequence for the given character set (encoding) and your data is sent as JSON (usually with UTF-8 encoding). According to your example, the RestClients BaseUrl must end in a /. When you - for example - have a base URL like http://localhost/test and a relative request URL like api/consumer, then the combined URL would be http://localhost/api/consumer, which probably isn't what you want.

Other than that, the only thing I can suggest is, that you might take a look at the raw request using Fiddler.

PS: I see that you use AddJsonBody. This function uses an internal (non-configurable) instance of the JsonSerializer and not the one configured in the RestRequest. When you want to use RestRequests serializer, then you should use AddBody instead of AddJsonBody.

dylinmaust commented 7 years ago

@fubar-coder Thanks for your response. I fought with this all day yesterday and a bit this morning and found that a Web API web config issue was causing HTTP 500 errors for requests that failed authentication (which wasn't logged via ELMAH), rather than returning a 401. So, this is not a bug at all, but rather a configuration issue on our side. Sorry for the trouble!