What would cause this custom XML ModelBinder to no

2020-04-16 03:05发布

问题:

The Model

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

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

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

The Application_Start() in Global.asax.cs

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

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

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

The Action

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

Yet when I POST a "text/xml" request containing this XML:

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

All I get back is:

, , , 0, False, {}

I followed this post, What am I missing here?

回答1:

What am I missing here?

You are missing to reset the stream before consuming it:

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

or use an XmlReader:

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