Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将XML发布到MVC控制器中?(而不是键/值)_Xml_Asp.net Mvc_Fiddler - Fatal编程技术网

如何将XML发布到MVC控制器中?(而不是键/值)

如何将XML发布到MVC控制器中?(而不是键/值),xml,asp.net-mvc,fiddler,Xml,Asp.net Mvc,Fiddler,用小提琴我可以通过身体 someXml=这应该是xml 然后在控制器中 [HttpPost] public ActionResult Test(object someXml) { return Json(someXml); } 以字符串形式获取此数据 如何让fiddler将XML传递给MVC ActionController?如果我尝试将正文中的值设置为原始xml,它将不起作用 如何从VBscript/Classic ASP获得额外积分 我现在有

用小提琴我可以通过身体

someXml=这应该是xml

然后在控制器中

    [HttpPost]
    public ActionResult Test(object someXml)
    {
        return Json(someXml);
    }
以字符串形式获取此数据

如何让fiddler将XML传递给MVC ActionController?如果我尝试将正文中的值设置为原始xml,它将不起作用

如何从VBscript/Classic ASP获得额外积分

我现在有

DataToSend = "name=JohnSmith"

          Dim xml
         Set xml = server.Createobject("MSXML2.ServerXMLHTTP")
   xml.Open "POST", _
             "http://localhost:1303/Home/Test", _
             False
 xml.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
 xml.send DataToSend

为了使用VBScript发送请求,我使用了WinHttp对象,即“WinHttp.WinHttpRequest.5.1”

下面是我编写的一个函数,它发送您传入的XML请求并返回响应:

' -----------------------------------------
' Method: sendRequest()
' Descrip: send the web service request as SOAP msg
' -----------------------------------------
Public Function sendRequest(p_SOAPRequest)
    Const METHOD_NAME = "sendRequest()"
    Dim objWinHttp
    Dim strResponse
    Dim URL
    URL = "http:someURL.com"
    Const WINHTTP_OPTION_SECURITY_FLAGS = 13056 '13056: Ignores all SSL Related errors 
    Const WinHttpRequestOption_SslErrorIgnoreFlags = 4 'http://msdn.microsoft.com/en-us/library/Aa384108

    Set objWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")

    'Open HTTP connection
    Call objWinHttp.Open("POST", URL, False)

    'Set request headers
    Call objWinHttp.setRequestHeader("Content-Type", m_CONTENT_TYPE)
    Call objWinHttp.setRequestHeader("SOAPAction", URL)

    'Ignore the requirement for a security certificate:
    'http://msdn.microsoft.com/en-us/library/windows/desktop/aa384086(v=vs.85).aspx
    objWinHttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = WINHTTP_OPTION_SECURITY_FLAGS

    'Send SOAP request
    On Error Resume Next
    objWinHttp.Send p_SOAPRequest

    If Err Then
        m_objLogger.error(METHOD_NAME & " error " & Err.Number & ": " & Err.Description)
        Err.Clear
    End If

    'disable error handling
    On Error GoTo 0

    'Get XML Response
    strResponse = objWinHttp.ResponseText

    'cleanup
    Set objWinHttp = Nothing

    sendRequest = strResponse
End Function

这似乎是向MVC控制器支付XML的方式


我尝试将其与WEB API一起使用,但未能成功,因此我不得不改用MVC“控制器”。

您不能将XML数据作为文件直接传递给MVC控制器。最好的方法之一是使用HTTPPOST将XML数据作为流传递

对于发布XML

  • 将XML数据转换为流并附加到HTTP头
  • 将内容类型设置为“text/xml;encoding='utf-8'”
  • 有关将XML发布到MVC控制器的更多详细信息,请参阅

    要在控制器中检索XML,请使用以下方法

    [HttpPost] 
    public ActionResult Index()
    {
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // as XML: deserialize into your own object or parse as you wish
            var responseXml = XDocument.Load(response.GetResponseStream());
    
            //in responseXml variable you will get the XML data
        }
    }
    

    为了在MVC中以sting的形式传递数据,您必须创建自己的媒体类型格式化程序来处理纯文本。然后将格式化程序添加到配置部分

    要使用新的格式化程序,请指定该格式化程序的内容类型,如 文本/纯文本

    文本格式化程序示例

    using System;
    using System.Net.Http.Formatting;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using System.IO;
    using System.Text;
    
    namespace SampleMVC.MediaTypeFormatters
    {
        public class TextMediaTypeFormmatter : XmlMediaTypeFormatter
        {
            private const int ByteChunk = 1024;
            private UTF8Encoding StringEncoder = new UTF8Encoding();
    
            public TextMediaTypeFormmatter()
            {
                base.UseXmlSerializer = true;
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
            }
    
            public override bool CanReadType(Type type)
            {
                if (type == typeof(string))
                {
                    return true;
                }
                return false;
            }
    
            public override bool CanWriteType(Type type)
            {
                if (type == typeof(string))
                {
                    return true;
                }
                return false;
            }
    
            public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
            {
                StringBuilder StringData = new StringBuilder();
                byte[] StringBuffer = new byte[ByteChunk];
                int BytesRead = 0;
    
                Task<int> BytesReadTask = readStream.ReadAsync(StringBuffer, 0, ByteChunk);
                BytesReadTask.Wait();
    
                BytesRead = BytesReadTask.Result;
                while (BytesRead != 0)
                {
                    StringData.Append(StringEncoder.GetString(StringBuffer, 0, BytesRead));
                    BytesReadTask = readStream.ReadAsync(StringBuffer, 0, ByteChunk);
                    BytesReadTask.Wait();
    
                    BytesRead = BytesReadTask.Result;
                }
    
                return Task<object>.Run(() => BuilderToString(StringData));
            }
    
            private object BuilderToString(StringBuilder StringData)
            {
                return StringData.ToString();
            }
    
            public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
            {
                byte[] StringBuffer = StringEncoder.GetBytes((string)value);
                return writeStream.WriteAsync(StringBuffer, 0, StringBuffer.Length);
            }
        }
    }
    
    Fiddler标题:

    User-Agent: Fiddler
    Content-Type: text/plain
    

    MVC控制器对于此类请求处理并不理想,但这就是任务所在,所以让我们开始吧。让我们来看一个我要接受的XML:

    <document>
    <id>123456</id>
        <content>This is document that I posted...</content>
        <author>Michał Białecki</author>
        <links>
            <link>2345</link>
            <link>5678</link>
        </links>
    </document>
    
    并在控制器中使用所有这些:

    public class DocumentsController : Controller
    {
        // documents/sendDocument
        [HttpPost]
        public ActionResult SendDocument()
        {
            try
            {
                var requestContent = GetRequestContentAsString();
                var document = XmlHelper.XmlDeserializeFromString<DocumentDto>(requestContent);
    
                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }
            catch (System.Exception)
            {
                // logging
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
        }
    
        private string GetRequestContentAsString()
        {
            using (var receiveStream = Request.InputStream)
            {
                using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    return readStream.ReadToEnd();
                }
            }
        }
    }
    
    公共类文档控制器:控制器
    {
    //文件/发送文件
    [HttpPost]
    公共行动结果SendDocument()
    {
    尝试
    {
    var requestContent=GetRequestContentAsString();
    var document=XmlHelper.XmlDeserializeFromString(requestContent);
    返回新的HttpStatusCodeResult(HttpStatusCode.OK);
    }
    捕获(系统异常)
    {
    //伐木
    返回新的HttpStatusCodeResult(HttpStatusCode.InternalServerError);
    }
    }
    私有字符串GetRequestContentAsString()
    {
    使用(var receiveStream=Request.InputStream)
    {
    使用(var readStream=newstreamreader(receiveStream,Encoding.UTF8))
    {
    返回readStream.ReadToEnd();
    }
    }
    }
    }
    
    要使用它,只需使用例如Postman发送请求。我正在用上面提到的xml正文向端点发送POST请求。值得一提的一个细节是标题。添加内容类型:text/xml或request to work

    它的工作原理是:


    你可以在我的博客上看到整个帖子:

    我查看了WinHttp.WinHttpRequest.5.1,但不确定如何安装它。。我已经让MSXML2.ServerXMLHTTP工作了。。只是我需要找到一种方法,将整个XML字符串传递给POST操作和有限的键/值对。当您尝试在正文中发送XML时,您将内容类型头设置为什么?如果您更新了您的问题,以显示您正在发送的Composer选项卡中的所有内容,这可能会有所帮助。如果找到答案,我需要一种方法将一段XML粘贴到键/值对中,并且使用ActionFilter似乎可行。。现在我只需要弄清楚如何在经典ASP中解析XML。。
    <document>
    <id>123456</id>
        <content>This is document that I posted...</content>
        <author>Michał Białecki</author>
        <links>
            <link>2345</link>
            <link>5678</link>
        </links>
    </document>
    
    public static class XmlHelper
    {
        public static T XmlDeserializeFromString<T>(string objectData)
        {
            var serializer = new XmlSerializer(typeof(T));
    
            using (var reader = new StringReader(objectData))
            {
                return (T)serializer.Deserialize(reader);
            }
        }
    }
    
    [XmlRoot(ElementName = "document", Namespace = "")]
    public class DocumentDto
    {
        [XmlElement(DataType = "string", ElementName = "id")]
        public string Id { get; set; }
    
        [XmlElement(DataType = "string", ElementName = "content")]
        public string Content { get; set; }
    
        [XmlElement(DataType = "string", ElementName = "author")]
        public string Author { get; set; }
    
        [XmlElement(ElementName = "links")]
        public LinkDto Links { get; set; }
    }
    
    public class LinkDto
    {
        [XmlElement(ElementName = "link")]
        public string[] Link { get; set; }
    }
    
    public class DocumentsController : Controller
    {
        // documents/sendDocument
        [HttpPost]
        public ActionResult SendDocument()
        {
            try
            {
                var requestContent = GetRequestContentAsString();
                var document = XmlHelper.XmlDeserializeFromString<DocumentDto>(requestContent);
    
                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }
            catch (System.Exception)
            {
                // logging
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
        }
    
        private string GetRequestContentAsString()
        {
            using (var receiveStream = Request.InputStream)
            {
                using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    return readStream.ReadToEnd();
                }
            }
        }
    }