-
Notifications
You must be signed in to change notification settings - Fork 11
自定义提交格式
Henry edited this page Oct 11, 2019
·
1 revision
在调用`WebApi`的时候都需要设置`Content-Type`并根据相关格式来写入数据;在返回获取的时候同样也是根据`Content-Type`来对数据进行处理。组件暂不会自动地处理这个环节,通过手动指定相信的数据处理器来完成,它的实现是承继于`FormaterAttribute`.组件提供两个处理器分别是:`FormUrlFormater`和`JsonFormater`.组件默认是使用`JsonFormater`.有些情况的处理比较特别,如是提交数据是`application/x-www-form-urlencoded`返回数据是`application/json`,这个时候就需要实现一个对应的`Formater`来适应这一情况。 FormaterAttribute
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Class)]
public abstract class FormaterAttribute : Attribute, IClientBodyFormater
{
public abstract string ContentType { get; }
public abstract void Serialization(object data, PipeStream stream);
public abstract object Deserialization(BeetleX.Buffers.PipeStream stream, Type type, int length);
}
public class JsonFormater : FormaterAttribute
{
public override string ContentType => "application/json";
public override object Deserialization(PipeStream stream, Type type, int length)
{
using (stream.LockFree())
{
if (type == null)
{
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(stream))
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault();
object token = jsonSerializer.Deserialize(reader);
return token;
}
}
else
{
using (StreamReader streamReader = new StreamReader(stream))
{
JsonSerializer serializer = JsonSerializer.CreateDefault();
object result = serializer.Deserialize(streamReader, type);
return result;
}
}
}
}
public override void Serialization(object data, PipeStream stream)
{
using (stream.LockFree())
{
using (StreamWriter writer = new StreamWriter(stream))
{
IDictionary dictionary = data as IDictionary;
JsonSerializer serializer = new JsonSerializer();
if (dictionary != null && dictionary.Count == 1)
{
object[] vlaues = new object[dictionary.Count];
dictionary.Values.CopyTo(vlaues, 0);
serializer.Serialize(writer, vlaues[0]);
}
else
{
serializer.Serialize(writer, data);
}
}
}
}
}