Please anyone give me some idea how following three modules work together in asp.net Web API 2.1
- Owin Middleware
- HttpMessageHandler (or DelegatingHandler)
- ExceptionHandler
What I am trying to do is to develop and a web api which will deliver a constant format json data, means if the actual data is
{"Id":1,"UserName":"abc","Email":"abc@xyz.com"}
Then I like to deliver json as
{__d:{"Id":1,"UserName":"abc","Email":"abc@xyz.com"}, code:200, somekey: "somevalue"}
For this I tried using custom ActionFilterAttribute but I feel(still not confirm) this could not deliver similarly formated data in case of code encounter an exception
Please suggest me best direction.
Here is my brief code snippet of custom attribute. Also suggest me is custom attribute is good for the purpose
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class ResponseNormalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
var response = actionExecutedContext.Response;
object contentValue;
if (response.TryGetContentValue(out contentValue))
{
var nval = new { data=contentValue, status = 200 };
var newResponse = new HttpResponseMessage { Content = new ObjectContent(nval.GetType(), nval, new JsonMediaTypeFormatter()) };
newResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
actionContext.Response = newResponse;
}
}
}