2013-07-30 57 views
18

使用招我可以在體內通過如何將XML發佈到MVC控制器? (而不是鍵/值)

someXml = ThisShouldBeXml

,然後在控制器

[HttpPost] 
    public ActionResult Test(object someXml) 
    { 
     return Json(someXml); 
    } 

得到這個數據作爲串

我如何得到提琴手將XML傳遞給MVC ActionController?如果我嘗試設置在身體的價值作爲原始xml它不起作用..

而對於獎勵點,如何從VBscript /經典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 
+1

當您嘗試在正文中發送XML時,您將Content-Type標頭設置爲什麼內容?如果您更新了問題以顯示您發送的Composer選項卡中的所有內容,可能會有所幫助。 – EricLaw

+0

找到了答案,我需要一種方法來在關鍵字/值對中粘貼一段XML,並使用ActionFilter似乎起作用。現在,我只需要弄清楚如何解析經典ASP中的XML。 – punkouter

回答

-1

爲了使用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 
+0

I看着那個WinHttp.WinHttpRequest.5.1,但不知道如何安裝它..我已經有MSXML2.ServerXMLHTTP工作..它只是我需要找到一種方法來傳遞整個XML字符串到POST動作和有限的關鍵/值對 – punkouter

8

您不能將XML數據作爲文件直接傳遞給MVC控制器。最好的方法之一是將XML數據作爲Stream傳遞給HTTP post。

張貼XML,

  1. XML數據轉換爲流,並連接到HTTP頭
  2. 集內容類型爲 「text/XML;編碼= 'UTF-8'」

參考this stackoverflow post爲更多細節發佈的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 
    } 
} 
2

爲了在MVC中傳遞數據,必須創建自己的媒體類型格式化程序來處理純文本。然後將格式化程序添加到配置部分。

要使用新格式化程序,請指定該格式化程序的Content-Type,如 text/plain

樣品格式化文本

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

控制器的方法:

config.Formatters.Add(new TextMediaTypeFormmatter()); 

提琴手標題:

User-Agent: Fiddler 
Content-Type: text/plain 
在WebApiConfig.cs註冊方法

[HttpPost] 
public async Task<HttpResponseMessage> UsingString([FromBody]string XmlAsString) 
{ 
    if (XmlAsString == null) 
    { 
     return this.Request.CreateResponse(HttpStatusCode.BadRequest); 
    } 

    return this.Request.CreateResponse(HttpStatusCode.OK, new { }); 
} 

設置

+0

這是爲我工作的方法。 –

相關問題