我有两个网站ABC和XYZ。我正在尝试将ABC的数据发送到XYZ。
具体功能:我使用EmailID登录后使用ABC应用程序。当我单击ABC应用程序中的按钮时,该站点应该与凭据一起重定向到XYZ站点。我通过标题以XML格式将数据发送到XYZ。
public async Task<object> Login()
{
string url = "http://localhost:49669/**api**/Account/PostData";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic Auth");
string xmlString = "";
UserDetails userDetail = new UserDetails { UserID = 1, EmailID = "name@redblacktree.com" };
XmlDocument xmlDoc = new XmlDocument(); //Represents an XML document,
//Initializes a new instance of the XmlDocument class.
XmlSerializer xmlSerializer = new XmlSerializer(userDetail.GetType());
var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
// Creates a stream whose backing store is memory.
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, userDetail, emptyNs);
xmlStream.Position = 0;
//Loads the XML document from the specified string.
xmlDoc.Load(xmlStream);
xmlString = xmlDoc.InnerXml;
}
var stringContent = new StringContent(xmlString.ToString(), Encoding.UTF8, "application/xml");
httpClient.DefaultRequestHeaders.Add("UserDetails", xmlString.ToString());
var response = httpClient.PostAsync(url, stringContent).Result;
var result = response.Content.ReadAsStringAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var messageContents = await response.Content.ReadAsStringAsync();
return Content(messageContents);
}
return null;
}
这里UserDetails是一个模型类。
public class AccountController : ApiController
{
[System.Web.Http.HttpPost]
public HttpResponseMessage PostData(HttpRequestMessage request)
{
var someText = request.Content.ReadAsStringAsync().Result;
var header1 = request.Headers.Authorization;
var header2 = request.Headers.GetValues("UserDetails");
return new HttpResponseMessage();
}
如果我要发布到API控制器,它可以正常工作。如果是普通的MVC控制器,则无法正常工作。任何人都可以告诉我原因。
我正在尝试发布到MVC控制器,因为我发现很难将API数据从API控制器传递到MVC控制器。因此,如果我可以直接发布到MVC控制器,它可以简化我的工作。有什么帮助吗?
答案 0 :(得分:0)
解决!
只需提供返回类型,因为ActionResult解决了我的问题。不必要的是我复杂了代码。
public class AccountController : Controller
{
[System.Web.Http.HttpPost]
public ActionResult PostData()
{
var data = HttpContext.Request.Headers["UserDetails"];
return null;
}
}
谢谢!