I have an
ApiController
public class SampleController : ApiController
{
[Route("api/Sample/")]
[HttpPost]
public HttpResponseMessage GetSampleInfo([FromBody]SampleClass sampleClassObject)
{
// Some code
}
}
Controller
Guid
Guid
00000000-0000-0000-0000-000000000000
x-www-form-urlencoded
application/json
{
"sampleID": "A9A999AA-AA99-9AA9-A999-9999999999AA",
"otherValue": 1
}
Guid
Guid
SampleClass
public class SampleClass
{
public Guid sampleID { get; set; }
public int otherValue { get; set; }
}
JsonConverter
public class GuidConverterCustom : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Guid) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.Null:
return Guid.Empty;
case JsonToken.String:
string str = reader.Value as string;
if (string.IsNullOrEmpty(str))
{
return Guid.Empty;
}
else
{
return new Guid(str);
}
default:
throw new ArgumentException("Invalid token type");
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (Guid.Empty.Equals(value))
{
writer.WriteValue("");
}
else
{
writer.WriteValue((Guid)value);
}
}
}
Global.asax.cs
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new GuidConverterCustom());
return settings;
};
Your method should look like this, no need for custom JsonConverter.
[Route("sample")]
[HttpPost]
public IHttpActionResult PostGuid(SampleClass id)
{
return Ok();
}
It then works with both x-www-form-urlencoded
and application/json
. If you use json do not forget the header Content-Type: application/json
.