Curiousity Curiousity - 2 years ago 272
C# Question

WebApi - Sent Guid taken as a new Guid

I have an

ApiController
class with a method accepting a complex object.

public class SampleController : ApiController
{
[Route("api/Sample/")]
[HttpPost]
public HttpResponseMessage GetSampleInfo([FromBody]SampleClass sampleClassObject)
{
// Some code
}
}


When debugging, this
Controller
class method is called, but what was passed as a
Guid
in the object, shows a new
Guid
(as
00000000-0000-0000-0000-000000000000
). I'm first checking this method with Postman. I tried passing the object using
x-www-form-urlencoded
and also as
application/json
.

What I'm passing in Postman:

{
"sampleID": "A9A999AA-AA99-9AA9-A999-9999999999AA",
"otherValue": 1
}


I checked other issues like mine but I have tried the solutions but still I'm getting the passed
Guid
as a new
Guid
.

P.S.
The
SampleClass
looks like as follows:

public class SampleClass
{
public Guid sampleID { get; set; }
public int otherValue { get; set; }
}


Update:

I have used the following
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);
}
}
}


And included the following in the
Global.asax.cs
:

JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new GuidConverterCustom());
return settings;
};

Answer Source

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.

enter image description here

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download