2013-10-01 3 views
1

몇 가지 비슷한 질문을 본 적이 있지만 해결 방법이 없습니다.웹 API 게시 XML 객체는 항상 null입니다.

이 코드는 JSON 페이로드를 전달할 때 완벽하게 작동합니다. 그러나 XML로드의 경우 컨트롤러 POST 메소드에 전달 된 객체는 항상 NULL입니다.

내 콘솔 앱은 내 ASP MVC 컨트롤러에 POST HTTP 요청을 보내고이 시점에서 전달 된 XML 페이로드 개체는 항상 null입니다.

는 HTTP 요청 객체를 보여주는 내 콘솔 응용 프로그램 설정되고 있으며 XML하여 XDocument 페이로드가 건설되고 :

[System.Web.Mvc.HttpPost] 
public string PostXML(object xmlPayload) 
{ 

    //*****The 'xmlPayLoad' object is always null***** 
    List<SplitXML> returnedPopulatedXMLObject = SetXMLstrings(XDocument.Parse(xmlPayload.ToString())); 

    foreach (var XMLitem in returnedPopulatedXMLObject) 
    { 
     _ClientID = XMLitem.ISIClientID; 

     _OrganizationID = XMLitem.OrganizationID; 

     _Status = XMLitem.Status; 
    } 

    string stringXDoc; 

    return stringXDoc = "POSTed"; 
} 

이는 다음과 같습니다

XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); 
    XElement clientRequestElement = new XElement(xmlns + "PLTSActivation", 
      new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
      new XElement(xmlns + "iSIClientID", iid.ToString()), 
      new XElement(xmlns + "organizationId", ooid), 
      new XElement(xmlns + "statusDescription", "Success")); 

    doc.Add(clientRequestElement); 

    return doc.ToString(SaveOptions.DisableFormatting); 
} 


public static void PostXML() 
{ 
    string _URL = "http://localhost:24689/api/PTShandler/postxml"; 

    string _OOID = "TEST"; 
    string convertedJSONPayload = ""; 

    var payloadObj = new 
    { 
     XmlPayload = ConstructProvisioningRequest(99783971, _OOID) 
    }; 

    try 
    { 
     var httpWebRequest = (HttpWebRequest)WebRequest.Create(_URL); 
       httpWebRequest.Headers.Add("ORGOID", _OOID); 
       httpWebRequest.Headers.Add("Culture", "en-US"); 
       httpWebRequest.ContentType = "application/xml"; 
       httpWebRequest.Accept = "application/xml"; 
       httpWebRequest.Method = "POST"; 


     using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
     { 
      streamWriter.Write(payloadObj.ToString()); 
      streamWriter.Flush(); 
      streamWriter.Close(); 
     } 
    } 

이 내 PTShandler 컨트롤러가 POST 방법을 보여주고있다 내 Global.asax.cs 파일 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 

namespace RESTful.CallBackService 
{ 
public class WebApiApplication : System.Web.HttpApplication 
{ 
     protected void Application_Start() 
     { 
      var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; 
      xml.UseXmlSerializer = true; 

      AreaRegistration.RegisterAllAreas(); 

      WebApiConfig.Register(GlobalConfiguration.Configuration); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 
     } 
} 
} 

그리고 내 App_Start WebApi입니다. Config.cs 파일 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 
using System.Xml.Serialization; 

namespace RESTful.CallBackService 
{ 
public static class WebApiConfig 
{ 
     public static void Register(HttpConfiguration config) 
     { 
      config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{action}/{id}", 
      defaults: new 
      { 
       id = RouteParameter.Optional 
      } 
     ); 
     } 
} 
} 

어디에서 잘못 된 지 알 수 있습니까?

+0

[피들러] (http://fiddler2.com/)를 발사하고 HTTP를 검사 해 보셨습니까? – Liam

답변

1

웹 요청의 모든 핵심 사항을 처리하는 대신 비즈니스 논리에 집중해야합니다. ServiceStack이라는 훌륭한 오픈 소스 프로젝트가 있습니다.이 프로젝트는 여러분에게 필요한 모든 것을 다룰 것입니다. 그런 다음 사용자가 사용하는 client(s)에 직렬화 된 객체 만 보내면됩니다. 웹 클라이언트는 처리기에서 비즈니스 개체 만 수신하지만 처리 방법 (어떤 프로토콜로)이 도착했는지 상관하지 않습니다. 양쪽 끝을 모두 제어하면 훨씬 좋습니다.

예, 당신은 당신은 웹 서비스에 안녕하세요 DTO 객체를 등록합니다 위의 here.의 더 나은 설명서 및 설명을 참조 XmlServiceClient

var client = new XmlServiceClient("http://host"); 

HelloResponse response = client.Post(new Hello { Name = "World" }); 

를 사용하는 XML 객체를 게시하고 그것을로 라우팅됩니다 Name과 같은 매개 변수를 기반으로하는 적절한 서비스.

예 위의 예에서 호스트가 다음과 같이 구성 될 수 있습니다. 따라서 브라우저에 입력 한 요청에 해당 URL이있을 수 있으며 이름이 채워진 Hello 객체가 Hello 웹 서비스에 제공됩니다.

0

Request.InputStream에서 xml을 가져 오십시오. 여기에는 원시 게시물 콘텐츠 (이 경우 XML)가 포함됩니다.

관련 문제