阅读文本/ XML转换为ASP.MVC控制器 [英] Reading text/xml into a ASP.MVC Controller

查看:98
本文介绍了阅读文本/ XML转换为ASP.MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何阅读的文本/ XML转换成一个ASP.MVC控制器?

How do I read text/xml into an action on a ASP.MVC Controller?

我有可能会从两个不同来源获得的xml POST方法因此XML的内容可能是不同的Web应用程序。

I have a web application that may receive POSTed Xml from two different sources so the contents of the Xml may be different.

我想在我的CONTROLER默认动作要能读,但是我很努力,看看我能得到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
    ...
}

这显然是清洁的。

which is obviously cleaner.

这篇关于阅读文本/ XML转换为ASP.MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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