Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api, How to return enum text value instead of enum index value from HttpResponseMessage

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 ?

like image 500
Arbejdsglæde Avatar asked Dec 01 '22 16:12

Arbejdsglæde


2 Answers

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());
  });
like image 106
Arturo Menchaca Avatar answered Dec 04 '22 16:12

Arturo Menchaca


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

like image 21
James Dev Avatar answered Dec 04 '22 18:12

James Dev