MVC3控制器具体JsonConverter [英] MVC3 Controller with specific JsonConverter

查看:118
本文介绍了MVC3控制器具体JsonConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的设置:

我有旨在由jQuery的Ajax请求被消耗一些MVC控制器。一个正常的请求将有所似乎是这样的:

  $。阿贾克斯(/律师/ AddSolicitorToApplication,{
    数据:putData,
    类型:POST,则contentType:应用/ JSON
    成功:函数(结果){
       //我的成功回调
        }
    }
});

我的控制器看起来是这样的:

  [HttpPost]
公众的ActionResult InsertLoanApplication(MortgageLoanApplicationViewModel VM)
{
   变种mortgageLoanDTO = vm.MapToDTO();
   返回JSON(_mortgageLoanService.UpdateMortgageLoanApplication(mortgageLoanDTO),JsonRequestBehavior.DenyGet);
}

这适用于传递给控制器​​的大多数对象完全正常的,但在这种特殊情况下对象的属性之一传递需要以特定的方式进行反序列化。

我添加了我使用previously与MVC4的Web API一个JsonConverter,但在这种情况下,我需要将其应用于常规MVC控制器。

我试过注册JsonConverter在我的Global.asax是这样的:

<$p$p><$c$c>GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new GrizlyStringConverter());

但到目前为止还没有能够反序列化对象。


解决方案

您应该更换内置的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonvalueproviderfactory%28v=vs.98%29.aspx\"相对=nofollow> JsonValueProviderFactory 与自定义,如果你想使用一个类 Json.NET 结合JSON请求时查看模型。

如图这个主旨你可以写一个:

 公共密封类JsonDotNetValueProviderFactory:ValueProviderFactory
{
    公众覆盖IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        如果(controllerContext == NULL)
        {
            抛出新的ArgumentNullException(controllerContext);
        }        如果(!controllerContext.HttpContext.Request.ContentType.StartsWith(应用/ JSON,StringComparison.OrdinalIgnoreCase))
        {
            返回null;
        }        使用(VAR读者=新的StreamReader(controllerContext.HttpContext.Request.InputStream))
        {
            变种bodyText的= reader.ReadToEnd();            返回String.IsNullOrEmpty(bodyText的)
                ?空值 :
                新DictionaryValueProvider&LT;对象&gt;(
                    JsonConvert.DeserializeObject&LT; ExpandoObject&GT;(
                        bodyText的,
                        新ExpandoObjectConverter()
                    )
                    CultureInfo.CurrentCulture
                );
        }
    }
}

,然后更换内置的与您的自定义之一的Application_Start

  ValueProviderFactories.Factories.Remove(
    ValueProviderFactories
        .Factories
        .OfType&LT; JsonValueProviderFactory&GT;()
        .FirstOrDefault()
);
ValueProviderFactories.Factories.Add(新JsonDotNetValueProviderFactory());

就是这样。现在,您使用的是Json.Net,而不是针对的JavaScriptSerializer传入的JSON请求。

Here's the setup:

I have some MVC Controllers that are intended to be consumed by jQuery ajax requests. A normal request would seem somewhat like this:

$.ajax("/Solicitor/AddSolicitorToApplication", {
    data: putData,
    type: "POST", contentType: "application/json",
    success: function (result) {
       //My success callback
        }
    }
});

My controller looks like this:

[HttpPost]
public ActionResult InsertLoanApplication(MortgageLoanApplicationViewModel vm)
{
   var mortgageLoanDTO = vm.MapToDTO();
   return Json(_mortgageLoanService.UpdateMortgageLoanApplication(mortgageLoanDTO),   JsonRequestBehavior.DenyGet);
}

This works perfectly fine with most objects passed to the controller, except that in this specific case one of the properties of the object being passed needs to be deserialized in a specific way.

I've added a JsonConverter that I've used previously with the MVC4 Web API, but in this case I need to apply it to regular mvc controllers.

I tried registering the JsonConverter in my global.asax like this:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new GrizlyStringConverter());

But so far haven't been able to deserialize the object.

解决方案

You should replace the built-in JsonValueProviderFactory class with a custom one if you want to use Json.NET when binding JSON requests to view models.

You could write one as shown in this gist:

public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
        {
            return null;
        }

        using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream))
        {
            var bodyText = reader.ReadToEnd();

            return String.IsNullOrEmpty(bodyText)
                ? null :
                new DictionaryValueProvider<object>(
                    JsonConvert.DeserializeObject<ExpandoObject>(
                        bodyText,
                        new ExpandoObjectConverter()
                    ),
                    CultureInfo.CurrentCulture
                );
        }
    }
}

and then replace the built-in with your custom one in Application_Start:

ValueProviderFactories.Factories.Remove(
    ValueProviderFactories
        .Factories
        .OfType<JsonValueProviderFactory>()
        .FirstOrDefault()
);
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());

That's it. Now you are using Json.Net instead of the JavaScriptSerializer for the incoming JSON requests.

这篇关于MVC3控制器具体JsonConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆