我已经看到了一些与此类似的问题,但没有一个解决方案对我有帮助。
当我传递 JSON 有效负载时,此代码完美运行。但是对于 XML 加载,传递给控制器 POST 方法的对象始终为 NULL。
我的控制台应用程序只是向我的 ASP MVC 控制器发出 POST http 请求,此时传递的 XML 有效负载对象始终为空。
这是我的控制台应用程序,显示正在设置的 http 请求对象和正在构造的 XML Xdocument 有效负载:
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 方法:
[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";
}
这是我的 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 WebApiConfig.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
}
);
}
}
}
谁能看到我哪里出错了?