Response.Redirect with POST instead of Get?

后端 未结 14 942
离开以前
离开以前 2020-11-22 04:04

We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to \"submit\" a form with POST, n

14条回答
  •  渐次进展
    2020-11-22 04:24

    Copy-pasteable code based on Pavlo Neyman's method

    RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one. The data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.

    Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application.

    My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.

            protected void RedirectPost(string url, IEnumerable> fields)
            {
                Response.Clear();
    
                const string template =
    @"
    
    
    {1}
    "; var fieldsSection = string.Join( Environment.NewLine, fields.Select(x => $"") ); var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection); Response.Write(html); Response.End(); } private const string JsonDataFieldName = "_jsonData"; protected void RedirectPost(string url, T bodyPayload) { var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented); //explicit type declaration to prevent recursion IEnumerable> postFields = new List>() {new KeyValuePair(JsonDataFieldName, json)}; RedirectPost(url, postFields); } protected T GetPostData() where T: class { var urlEncodedFieldData = Request.Params[JsonDataFieldName]; if (string.IsNullOrEmpty(urlEncodedFieldData)) { return null;// default(T); } var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData); var result = JsonConvert.DeserializeObject(fieldData); return result; }

提交回复
热议问题