将 text/xml 读入 ASP.MVC 控制器 [英] Reading text/xml into a ASP.MVC Controller
问题描述
如何将 text/xml 读入 ASP.MVC 控制器上的操作?
How do I read text/xml into an action on a ASP.MVC Controller?
我有一个 Web 应用程序,它可能会从两个不同的来源接收 POSTed Xml,因此 Xml 的内容可能不同.
I have a web application that may receive POSTed Xml from two different sources so the contents of the Xml may be different.
我希望我的控制器上的默认操作能够读取 Xml,但是我正在努力了解如何首先将 Xml 放入操作中.
I want the default action on my controler to be able to read the Xml however I am struggling to see how I can get the Xml into the action in the first place.
如果 Xml 是一致的,我可以使用模型绑定器,但在这里不可能.
If the Xml was consistent I could have used a Model Binder but thats not possible here.
推荐答案
您可以从请求流中读取:
You could read it from the request stream:
[HttpPost]
public ActionResult Foo()
{
using (var reader = new StreamReader(Request.InputStream))
{
string xml = reader.ReadToEnd();
// process the XML
...
}
}
并且要清除此操作,您可以为 XDocument 编写自定义模型绑定器:
and to cleanup this action you could write a custom model binder for a XDocument:
public class XDocumentModeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return XDocument.Load(controllerContext.HttpContext.Request.InputStream);
}
}
您将在 Application_Start
中注册:
ModelBinders.Binders.Add(typeof(XDocument), new XDocumentModeBinder());
最后:
[HttpPost]
public ActionResult Foo(XDocument doc)
{
// process the XML
...
}
这显然更干净.
这篇关于将 text/xml 读入 ASP.MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!