将text/xml读入ASP.MVC控制器

Sha*_*ady 6 xml asp.net-mvc action controller

如何将text/xml读入ASP.MVC控制器上的操作?

我有一个Web应用程序可以从两个不同的源接收POSTed Xml,因此Xml的内容可能不同.

我希望我的控制器上的默认操作能够读取Xml但是我很难看到我如何能够首先将Xml放入操作中.

如果Xml是一致的,我可以使用Model Binder,但这不可能.

Dar*_*rov 14

您可以从请求流中读取它:

[HttpPost]
public ActionResult Foo()
{
    using (var reader = new StreamReader(Request.InputStream))
    {
        string xml = reader.ReadToEnd();
        // process the XML
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

要清理此操作,您可以为XDocument编写自定义模型绑定器:

public class XDocumentModeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return XDocument.Load(controllerContext.HttpContext.Request.InputStream);
    }
}
Run Code Online (Sandbox Code Playgroud)

你要注册的Application_Start:

ModelBinders.Binders.Add(typeof(XDocument), new XDocumentModeBinder());
Run Code Online (Sandbox Code Playgroud)

最后:

[HttpPost]
public ActionResult Foo(XDocument doc)
{
    // process the XML
    ...
}
Run Code Online (Sandbox Code Playgroud)

这显然更清洁.