I notice that my Web Api method that return HttpResponseMessage convert enum value to int (order of value). But I would like to return enum text value.
return Request.CreateResponse(HttpStatusCode.OK, new {MyEnum.Someting, MyEnum.Someting2});
What should I setup for it ?
If you are returning and receiving the data in Json
, you can use StringEnumConverter
. Defining a model like this:
class Output
{
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public MyEnum[] Enums { get; set; }
}
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, new Output { Enums = new MyEnum[] { MyEnum.Someting, MyEnum.Someting2 } }); ;
}
Allows you instruct the json serializer to converts enums to and from its name string value.
Moreover, if you do not want to define the output model, in your WebApiConfig.Register(config)
method, you can add this lines and also works:
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
and for .Net Core Web API use this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions( op => {
op.SerializerSettings.Converters.Add(new StringEnumConverter());
});
You can use the Enum.GetName method
return Request.CreateResponse(HttpStatusCode.OK, new {Enum.GetName(typeof(MyEnum), 0), Enum.GetName(typeof(MyEnum), 1)});
If this is what you are looking for ? https://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.110).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With