简体   繁体   中英

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 ?

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

This will return the name of a value defined in MyEnum :

return Request.CreateResponse(HttpStatusCode.OK, 
    new string[] {MyEnum.Someting.ToString(), MyEnum.Someting2.ToString()});

If you have a number of variables of type MyEnum , then you can simply to a ToString on those variables:

MyEnum var1 = MyEnum.Something;
MyEnum var2 = MyEnum.Something2;

return Request.CreateResponse(HttpStatusCode.OK, 
       new string[] {var1.ToString(), var2.ToString()});

If you wanted to return the names of each value defined in MyEnum you can use:

return Request.CreateResponse(HttpStatusCode.OK, Enum.GetNames(typeof(MyEnum)));

You could add the following helper method:

public static class Enums
{
    public static string GetDescription(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

Then include descriptions in your enum, such as this:

public enum MyEnum
{
    [Description("Something 1")]
    Something1 = 1,
    [Description("Something 2")]
    Something2 = 2
}

And finally simply call:

return Request.CreateResponse(HttpStatusCode.OK, new 
{ 
    MyEnum.Something1.GetDescription(), 
    MyEnum.Something2.GetDescription()
});

I've created an extension for enums :

public static class EnumExtension
{
    public static string GetDescription(this Enum @enum)
    {
        FieldInfo fi = @enum.GetType().GetField(@enum.ToString());

        if (null != fi)
        {
            object[] attrs = fi.GetCustomAttributes
                (typeof (DescriptionAttribute), true);
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute) attrs[0]).Description;
        }
        return null;
    }

    public static IEnumerable<TEnum> GetAllValues<TEnum>()
    {
        return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
    }
}

Your Enum :

public enum MyEnum
{
    [Description("foobar1 text")]
    foobar1= 1,
    [Description("foobar2 text")]
    foobar2= 2,
    [Description("foobar3 text")]
    foobar3= 3,
    [Description("foobar4 text")]
    foobar3= 4
}

Then call like this :

 MyEnum.foobar2.GetDescription()

Should return foobar2 text

Other solution is :

Enum.GetName(typeof(MyEnum.foobar2)) 

to return foobar2

return Request.CreateResponse(HttpStatusCode.OK, new { TextValueOfSomething = MyEnum.Someting.ToString(), TextValueOfSomething2 = MyEnum.Someting2.ToString() });

You can't return new {MyEnum.Something.ToString(), MyEnum.Something2.ToString()} because you can't declare an anoymous object in this way. If you just want an array of strings then you would use new[] {MyEnum.Something.ToString(), MyEnum.Something2.ToString()} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM