简体   繁体   English

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

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

I've created simple model with JsonConverter attribute: 我用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; }
}

and my converter: 和我的转换器:

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);
    }
}

When I send request from Postman and I set content type as application/json everything works fine - my converter works fine, debugger stops at breakpoint in my converter, but I must use x-www-form-urlencoded . 当我从Postman发送请求并将内容类型设置为application/json一切正常 - 我的转换器工作正常,调试器在我的转换器中的断点处停止,但我必须使用x-www-form-urlencoded

Is there an option to use JsonConverter attribute inside model when sending data as x-www-form-urlencoded ? 在将数据作为x-www-form-urlencoded发送时,是否可以选择在模型中使用JsonConverter属性?

I managed to do this by creating custom model binder that implements IModelBinder 我设法通过创建实现IModelBinder的自定义模型绑定器来实现此目的

Here is generic version of my binder: 这是我的活页夹的通用版本:

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;
    }
}

And here is sample usage: 以下是示例用法:

[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();
    }
}

I'm not sure if JsonProperty and JsonConverter attributes worked, but they should. 我不确定JsonProperty和JsonConverter属性是否有效,但他们应该这样做。

I'm aware that this might not be the best way to do it, but this code worked for me. 我知道这可能不是最好的方法,但这段代码对我有用。 Any suggestion are more than welcome. 任何建议都非常受欢迎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Windows 手机 8.1 POST x-www-form-urlencoded 不起作用 - Windows phone 8.1 POST x-www-form-urlencoded not working Xawww中的x-www-form-urlencoded - x-www-form-urlencoded in Xamarin WebAPI DataMember通过application / x-www-form-urlencoded进行de / serial化时未使用的名称 - WebAPI DataMember Name not used when de/serializing via application/x-www-form-urlencoded C#-WebApi2-发布和获取-发布未将x-www-form-urlencoded转换为对象 - C# - WebApi2 - Post and Get - Post is not converting x-www-form-urlencoded to object Web API和应用程序/ x-www-form-urlencoded JSON - Web API and application/x-www-form-urlencoded JSON 在POST方法,HttpClient中使用application / x-www-form-urlencoded - use of application/x-www-form-urlencoded in POST method, HttpClient 如何将application / x-www-form-urlencoded转换为JSON? - How to convert application/x-www-form-urlencoded to JSON? 在 Minimal API NET 6 中接受 x-www-form-urlencoded - Accept x-www-form-urlencoded in Minimal API NET 6 WCF服务调用忽略了x-www-form-urlencoded响应 - x-www-form-urlencoded response ignored by WCF Service call 使用应用程序/ x-www-form-urlencoded的HTTPWebResponse - HTTPWebResponse using application/x-www-form-urlencoded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM