什么会导致此自定义XML ModelBinder不反序列化我的XML POST?

时间:2011-07-14 14:33:25

标签: asp.net-mvc-3 modelbinders xml-deserialization

模型

public class SimpleUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public int Role { get; set; }
    public bool isActive { get; set; }

    public string Groups { get; set; }
 }

BinderProvider

public class SimpleUserProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(Type modelType)
    {
        var contentType = HttpContext.Current.Request.ContentType;

        if (string.Compare(contentType, @"text/xml", StringComparison.OrdinalIgnoreCase) != 0)
        {
            return null;
        }

        return new SimpleUserBinder();
    }
}

ModelBinder

public class SimpleUserBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var modelType = bindingContext.ModelType;
        var serializer = new XmlSerializer(modelType);

        var inputStream = controllerContext.HttpContext.Request.InputStream;

        return serializer.Deserialize(inputStream);
    }
}

Global.asax.cs中的Application_Start()

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        ModelBinderProviders.BinderProviders.Add(new SimpleUserProvider());

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

行动

[HttpPost]
    public ActionResult Create(SimpleUser u)
    {
        //simple output for testing bind

        return Content(u.FirstName + ", " + u.LastName + ", " + u.UserName + ", " + u.Role.ToString() + ", " + u.isActive + ", {" + u.Groups + "}", "text/plain");
    }

然而,当我发布包含此XML的“text / xml”请求时:

<SimpleUser>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
<UserName>jsmith@someland.com</UserName>
<Role>3</Role>
<isActive>true</isActive>
</SimpleUser>

我得到的全部是:

  

,,, 0,False,{}

我跟着this post,我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

  

我在这里缺少什么?

在使用流之前,您缺少重置流:

var inputStream = controllerContext.HttpContext.Request.InputStream;
inputStream.Position = 0;
return serializer.Deserialize(inputStream);

或使用XmlReader

using (var inputStream = controllerContext.HttpContext.Request.InputStream)
using (var reader = XmlReader.Create(inputStream))
{
    return serializer.Deserialize(reader);
}