I am using ASP.NET web api. To provide support for camel case for the properties that an end point returns, I have added this code:
//Support camel casing
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
This is working fine but I want to add an exception for one of the endpoints. Which will ensure when the data is returned from that end point, properties are not camel cased. How can I add this exception or a single endpoint?
It's not possible to make control if you are applying a global camel case configuration
AFAK the only way to achieve this is by using ActionFilterAttribute
something like the following
public class CamelCasingFilterAttribute:ActionFilterAttribute
{
private JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();
public CamelCasingFilterAttribute()
{
_camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
if (content != null)
{
if (content.Formatter is JsonMediaTypeFormatter)
{
actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, _camelCasingFormatter);
}
}
}
}
public class ValuesController : ApiController
{
// GET api/values
[CamelCasingFilter]
public IEnumerable<Test> Get()
{
return new Test[] {new Test() {Prop1 = "123", Prop2 = "3ERr"}, new Test() {Prop1 = "123", Prop2 = "3ERr"}};
}
// GET api/values/5
public Test Get(int id)
{
return new Test() {Prop1 = "123", Prop2 = "3ERr"};
}
}
public class Test
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
if you try to call the first action the answer will like the follwing
[{"prop1":"123","prop2":"3ERr"},{"prop1":"123","prop2":"3ERr"}]
and for the second action given that there is no filter you will get something like this
{
"prop1": "123",
"prop2": "3ERr"
}
Note if you want to make it easy controlling camelCase over an entire controller, try to put your action that you want it to send back the answer in a not CamelCase in a controller apart but, for the rest apply this Filter on a controller level if you want. More you should delete the GlobalConfiguration to get this
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.