在下面的代码中,我手动创建一个遵循我们标准json响应对象格式的json对象,这对于错误和实际响应都是相同的:
{ data : { /*something*/ }, status : { httpCode : 123, message: "error message" } }
如何配置ASP.NET为我做这种格式化?显然,它可以在进行内容协商时使用标准的JSON和XML格式化程序来执行此操作,但是链接的文章仅指向自定义格式化程序上的空白页面(对于我未使用的ASP.NET MVC,也是如此)...
我还希望它能够在响应对象中设置返回的http代码(如下所示)。
当前json的手动格式
[StandardizedRestServiceExceptionFilter]
public class FooController : ApiController
{
/// <summary>
///
/// The return format for both real results and errors
/// is { data : { }, status : { httpCode : 123, message: "error message" }
///
/// We have moved the error serialization to StandardizedRestServiceExceptionFilter,
/// but was unable to generalize the processing of the output format for normal responses
/// That could be improved, possibly using a IMessageFormatter ?
/// </summary>
/// <param name="code"></param>
/// <returns></returns
[HttpGet]
public JObject Coverage(string code)
{
dynamic returnObject = new JObject();
dynamic statusObject = new JObject();
dynamic dataObject = new JObject();
JArray stores = StoresWithCoverage(code);
var hasCoverage = stores.Count > 0;
dataObject.coverage = hasCoverage;
returnObject.data = dataObject;
returnObject.status = statusObject;
statusObject.message = "";
statusObject.httpCode = 200;
return returnObject;
}
}
}
因此,在上面的示例中,我希望能够仅返回带有coverage
属性的某种Object,并让ASP.NET对JSON进行实际的格式设置和序列化(如果在内容协商中要求)。
可以使用ASP.NET Web API使用预建的或自定义的媒体格式化程序。
在这种情况下,可以以上面链接中的自定义格式器为例,并根据需要修改JSON内容包装器(此处:using JSON.NET):
首先,您需要指定要支持的内容类型:
public CustomJsonFormatter()
{
// Add the supported media type.
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
然后,您需要实现对WriteToStream
方法的重写:
public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
{
using (var writer = new StreamWriter(writeStream, effectiveEncoding))
{
using (JsonWriter jw = new JsonTextWriter(writer))
{
dynamic returnObject = new JObject();
dynamic status = new JObject();
JObject data = (JObject)JToken.FromObject(value);
status.httpCode = HttpContext.Current.HttpResponse.StatusCode;
status.message = null;
returnObject.data = data;
returnObject.status = status;
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
// for customizing settings, like lower casing
// attribute names, see http://stackoverflow.com/a/6288726/200987
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver()
serializer.Serialize(jw, returnObject);
}
}
}
最后,我们需要说出哪种类型支持转换,并向ASP.NET注册该格式化程序,以及进行其他一些较小的(通常是不需要的)修改。请参阅下面的文章,以了解如何执行此操作以及序列化,http状态代码和内容协商的工作方式并可以对其进行自定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句