I want to have uniform response for my all APIs (e.g. Count of records, records wrapped up in placeholder, no of errors if any encountered during processing of API request etc).
Json:
{"errors":[],"result":[ {"responseMessage":null,"responseType":null } ],"count":467 }
I'm using below code (MessagingHandler) to add metadata to response.
//Handler that wraps response of API in Result placeholder and adds count to it. public class ResponseWrappingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); return BuildApiResponse(request, response); } private HttpResponseMessage BuildApiResponse(HttpRequestMessage request, HttpResponseMessage response) { IEnumerable<object> content; response.TryGetContentValue(out content); //Content negotiation - to return response in the requested format var formatter = GlobalConfiguration.Configuration.Formatters.First( t => t.SupportedMediaTypes.Contains(new MediaTypeHeaderValue(response.Content.Headers.ContentType.MediaType))); var responsePackage = new ResponsePackage<object>(content, (content as IEnumerable<object>).Count()); var newResponse = request.CreateResponse<ResponsePackage<object>>(response.StatusCode, responsePackage, formatter); foreach (var header in response.Headers) //Add back the response headers { newResponse.Headers.Add(header.Key, header.Value); } return newResponse; } } //Can not add all the models as KnownType to avoid errors, any alternative? [KnownType(typeof(PersonResponse))] public class ResponsePackage<T> where T: class { public IEnumerable<T> Result { get; set; } public int Count { get; set; } public ResponsePackage() { } public ResponsePackage(IEnumerable<T> result, int count) { Result = result; Count = count; } }
However with above code, response in XML adds prefix and namespace to all the tags. Please refer below response:
<ResponsePackageOfanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Dummy.WebApi.Models.Common"><Count>467</Count><Errors xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" /><Result xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><d2p1:anyType xmlns:d3p1="http://schemas.datacontract.org/2004/07/Dummy.WebApi.Models" i:type="d3p1:PersonResponse"><d3p1:FirstName>Test</d3p1:FirstName><d3p1:FirstName>Test 1</d3p1:FirstName></d2p1:anyType>
Is there anyway that we can avoid namespace and prefix?
Awaiting response at the earliest.