using System.Collections.Specialized; using System.Net; using System.Text; using Microsoft.AspNetCore.Http; using Nop.Core; namespace Nop.Web.Framework; /// /// Represents a RemotePost helper class /// public partial class RemotePost { protected readonly IHttpContextAccessor _httpContextAccessor; protected readonly IWebHelper _webHelper; /// /// Gets or sets a remote URL /// public string Url { get; set; } /// /// Gets or sets a method /// public string Method { get; set; } /// /// Gets or sets a form name /// public string FormName { get; set; } /// /// Gets or sets a form character-sets the server can handle for form-data. /// public string AcceptCharset { get; set; } /// /// A value indicating whether we should create a new "input" HTML element for each value (in case if there are more than one) for the same "name" attributes. /// public bool NewInputForEachValue { get; set; } /// /// Parames /// public NameValueCollection Params { get; } /// /// Creates a new instance of the RemotePost class /// /// HTTP Context accessor /// Web helper public RemotePost(IHttpContextAccessor httpContextAccessor, IWebHelper webHelper) { Params = new NameValueCollection(); Url = "http://www.someurl.com"; Method = "post"; FormName = "formName"; _httpContextAccessor = httpContextAccessor; _webHelper = webHelper; } /// /// Adds the specified key and value to the dictionary (to be posted). /// /// The key of the element to add /// The value of the element to add. public void Add(string name, string value) { Params.Add(name, value); } /// /// Post /// public void Post() { //text var sb = new StringBuilder(); sb.Append(""); sb.Append($""); if (!string.IsNullOrEmpty(AcceptCharset)) { //AcceptCharset specified sb.Append( $"
"); } else { //no AcceptCharset specified sb.Append($""); } if (NewInputForEachValue) { foreach (string key in Params.Keys) { var values = Params.GetValues(key); if (values != null) { foreach (var value in values) { sb.Append( $""); } } } } else { for (var i = 0; i < Params.Keys.Count; i++) sb.Append( $""); } sb.Append("
"); sb.Append(""); var data = Encoding.UTF8.GetBytes(sb.ToString()); //modify the response var httpContext = _httpContextAccessor.HttpContext; var response = httpContext.Response; //post response.Clear(); response.ContentType = "text/html; charset=utf-8"; response.ContentLength = data.Length; response.Body .WriteAsync(data, 0, data.Length) .Wait(); //store a value indicating whether POST has been done _webHelper.IsPostBeingDone = true; } }