簡體   English   中英

WebAPI JsonConverter for x-www-form-urlencoded無法正常工作

[英]WebAPI JsonConverter for x-www-form-urlencoded not working

我用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屬性是否有效,但他們應該這樣做。

我知道這可能不是最好的方法,但這段代碼對我有用。 任何建議都非常受歡迎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM