【发布时间】:2011-11-28 21:57:28
【问题描述】:
有人尝试在 MVC 应用程序中添加自定义 Http Header,我会将表单操作设置为第三方 URL,第三方 URL 需要一些特定的自定义 Http Header。并且用户从 MVC 应用程序提交表单后,上下文也必须切换到第三方 URL。
我需要构建 MVC 应用程序并从服务器端读取值并最终将它们组合到标题中并提交表单。
谢谢
哈迪
【问题讨论】:
标签: asp.net-mvc-3
有人尝试在 MVC 应用程序中添加自定义 Http Header,我会将表单操作设置为第三方 URL,第三方 URL 需要一些特定的自定义 Http Header。并且用户从 MVC 应用程序提交表单后,上下文也必须切换到第三方 URL。
我需要构建 MVC 应用程序并从服务器端读取值并最终将它们组合到标题中并提交表单。
谢谢
哈迪
【问题讨论】:
标签: asp.net-mvc-3
使用 HTML <form> 元素时,您无法添加自定义标题。在这方面,HTML 规范没有提供任何内容。
添加自定义标头的唯一方法是使用WebClient 或HttpWebRequest 从您的ASP.NET MVC 应用程序向第三方站点执行POST 请求。两者都允许您在对给定 url 执行 HTTP 请求时设置自定义 HTTP 标头。显然,缺点是您代表服务器应用程序而不是客户端执行请求,因此切换上下文可能具有挑战性。
根据您的具体情况(您没有详细说明),可能有不同的方法可以尝试解决问题。
【讨论】:
根据您的问题,您应该使用自定义 HTTP 请求将此信息发布到第三方网站。
您可以通过使用 HttpWebRequest 处理表单发布并使用操作结果与用户共享确认来直接在操作内执行此操作。
如:
public ActionResult PostTest()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
return View(responseFromServer);
}
【讨论】: