2013-07-30 3 views
18

Uso Fiddler posso passare nel corpoCome caricare POST XML nel controller MVC? (Invece di chiave/valore)

someXml = ThisShouldBeXml

e poi nel controllore

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

riceve questi dati come una stringa

Come faccio a convincere il violinista a passare XML a MVC ActionController? Se provo ad impostare il valore nel corpo come xml non funziona.

E per i punti bonus come faccio questo da VBscript/ASP classico?

Attualmente ho

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

a cosa hai impostato l'intestazione Content-Type quando stavi cercando di inviare XML nel corpo? Potrebbe essere utile se hai aggiornato la tua domanda per mostrare tutto nella scheda Compositore che stai inviando. – EricLaw

+0

trovato la risposta, avevo bisogno di un modo per attaccare un pezzo di XML nella coppia chiave/valore e l'utilizzo di ActionFilter sembra funzionare .. Ora ho solo bisogno di capire come analizzare l'XML in Classic ASP .. – punkouter

risposta

-1

Per inviare la richiesta utilizzando VBScript Ho usato l'oggetto WinHttp cioè "WinHttp.WinHttpRequest.5.1".

Qui di seguito è una funzione che ho scritto, e questo invia la richiesta XML che si passa e restituisce la risposta:

' ----------------------------------------- 
' 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 ha esaminato WinHttp.WinHttpRequest.5.1 ma non ero sicuro di come installarlo .. Ho già MSXML2.ServerXMLHTTP in funzione ... è solo che ho bisogno di trovare un modo per passare un'intera stringa XML all'azione POST e alla chiave limitata coppia/valore – punkouter

8

Non è possibile passare direttamente dati XML come file al controller MVC. Uno dei metodi migliori è passare i dati XML come Stream con post HTTP.

per la pubblicazione di XML,

  1. Convertire i dati XML ad un ruscello e attaccato al HTTP Header
  2. Impostare il tipo di contenuto "text/xml; encoding = 'utf-8'"

Fare riferimento alla this stackoverflow post per maggiori dettagli sulla pubblicazione XML per MVC controller

per recuperare XML nel controller, utilizzare il seguente metodo

[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

Per passare i dati come una puntura in MVC è necessario creare il proprio formattatore di tipo di supporto per gestire il testo normale. Quindi aggiungere il formattatore alla sezione di configurazione.

Per utilizzare il nuovo formattatore specificare il tipo di contenuto per tale formattatore, ad esempio text/plain.formattatore

Esempio per il testo

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

Controller:

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

Setup nel metodo WebApiConfig.cs Register:

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

Fiddler intestazioni:

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

Questo è il metodo che ha funzionato per me. –