WebAPI JsonConverter for x-www-form-urlencoded not working
本文关键字:not working x-www-form-urlencoded for JsonConverter WebAPI | 更新日期: 2023-09-27 18:09:52
我创建了一个简单的模型,JsonConverter
属性:
public class MyModel
{
[JsonProperty(PropertyName = "my_to")]
public string To { get; set; }
[JsonProperty(PropertyName = "my_from")]
public string From { get; set; }
[JsonProperty(PropertyName = "my_date")]
[JsonConverter(typeof(UnixDateConverter))]
public DateTime Date { get; set; }
}
和我的转换器:
public sealed class UnixDateConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (!CanConvert(reader.ValueType))
{
throw new JsonSerializationException();
}
return DateTimeOffset.FromUnixTimeSeconds((long)reader.Value).ToUniversalTime().LocalDateTime;
}
public override bool CanConvert(Type objectType)
{
return Type.GetTypeCode(objectType) == TypeCode.Int64;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var datetime = (DateTime) value;
var dateTimeOffset = new DateTimeOffset(datetime.ToUniversalTime());
var unixDateTime = dateTimeOffset.ToUnixTimeSeconds();
writer.WriteValue(unixDateTime);
}
}
当我从Postman发送请求并将内容类型设置为application/json
时,一切工作正常-我的转换器工作正常,调试器在转换器的断点处停止,但我必须使用x-www-form-urlencoded
。
当发送数据为x-www-form-urlencoded
时,是否有一个选项在模型内使用JsonConverter
属性?
我设法通过创建实现IModelBinder的自定义模型绑定器来做到这一点
这是我的活页夹的通用版本:
internal class GenericModelBinder<T> : IModelBinder where T : class, new()
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof (T))
{
return false;
}
var model = (T) bindingContext.Model ?? new T();
JObject @object = null;
var task = actionContext.Request.Content.ReadAsAsync<JObject>().ContinueWith(t => { @object = t.Result; });
task.Wait();
var jsonString = @object.ToString(Formatting.None);
JsonConvert.PopulateObject(jsonString, model);
bindingContext.Model = model;
return true;
}
}
下面是示例用法:
[Route("save")]
[HttpPost]
public async Task<IHttpActionResult> Save([ModelBinder(typeof (GenericModelBinder<MyModel>))] MyModel model)
{
try
{
//do some stuff with model (validate it, etc)
await Task.CompletedTask;
DbContext.SaveResult(model.my_to, model.my_from, model.my_date);
return Content(HttpStatusCode.OK, "OK", new TextMediaTypeFormatter(), "text/plain");
}
catch (Exception e)
{
Debug.WriteLine(e);
Logger.Error(e, "Error saving to DB");
return InternalServerError();
}
}
我不确定是否JsonProperty和JsonConverter属性工作,但他们应该。
我知道这可能不是最好的方法,但这段代码对我来说很有效。欢迎有任何建议