2011-11-28 124 views
0

有人试图添加自定义的HTTP头中的MVC应用程序,我将设置表单动作为第三方网址,第三方URL期待一定的定制HTTP头。在用户从MVC应用程序提交表单后,上下文也必须切换到第三方URL。MVC3 HTTP POST到一个第三方网站,并添加自定义HTTP标头

我需要建立从服务器端的MVC应用程序和阅读价值,并最终在标题撰写他们并提交表单。

感谢

哈迪

回答

1

使用HTML <form>元素时,不能添加自定义页眉。 HTML规范在这方面没有什么可提供的。

添加自定义标头的唯一方法是使用WebClientHttpWebRequest从ASP.NET MVC应用程序向第三方站点执行POST请求。两者都允许您在对给定url执行HTTP请求时设置自定义HTTP标头。显然,缺点是你代表你的服务器应用程序而不是客户端执行请求,所以切换上下文可能是有挑战性的。

根据您的具体特定的方案(你还没有详细的)可能有不同的方式来试图解决这个问题。

+0

是的,切换的上下文是我关心的。用户从MVC应用程序提交表单后,用户必须在浏览器中看到第三方网站。我做了更多的研究(例如http://stackoverflow.com/questions/581383/adding-custom-http-headers-using-javascript)我觉得我可能会使用客户端的javaScript来提交表单。 – hardywang

+0

@hardywang,没有你不能使用JavaScript由于[同源策略(http://en.wikipedia.org/wiki/Same_origin_policy)限制,这将很快让你失望。您无法发送跨域AJAX请求。我会建议你不要浪费你的时间与JavaScript。 –

0

从你的问题的声音,你应该发布使用自定义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); 
     } 

参见MSDN on how to use HttpWebRequest to send HTTP Post forms

+0

HttpWebRequest不会将上下文切换到第三方URL。我在这里看到你的解决方案,基本上你的想法是使用服务器请求(使用自定义标题)并将内容作为字符串显示在UI上。让我担心的是,所有链接,来自第三方URL的图片路径都将被转换为本地链接和图片,而这些链接和图片根本不存在。 – hardywang

+0

@hardywang是啊,这只是一个快速的想法,因为我不知道你想直接完成什么。是否有任何理由需要向用户展示整个网站?你可以只显示某种确认页面,并只嵌入这些项目?否则,是的,如果你在页面中做了原始转储,那么链接就会关闭,就像我在答案中显示的那样。 –

+0

一旦用户将表单提交给第三方网址,我完成了我的工作,用户应该直接与其他方工作。 – hardywang