Sto cercando di passare JSON da jQuery a un file .ASHX. Esempio di jQuery di seguito:
$.ajax({ type: "POST", url: "/test.ashx", data: "{'file':'dave', 'type':'ward'}", contentType: "application/json; charset=utf-8", dataType: "json", });
Come posso recuperare i dati JSON nel mio file .ASHX? Ho il metodo:
public void ProcessRequest(HttpContext context)
ma non riesco a trovare i valori JSON nella richiesta.
So che questo è troppo vecchio, ma per la cronaca vorrei aggiungere i miei 5 centesimi
Puoi leggere l’object JSON sul server con questo
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
La seguente soluzione ha funzionato per me:
Dalla parte del cliente:
$.ajax({ type: "POST", url: "handler.ashx", data: { firstName: 'stack', lastName: 'overflow' }, // DO NOT SET CONTENT TYPE to json // contentType: "application/json; charset=utf-8", // DataType needs to stay, otherwise the response object // will be treated as a single string dataType: "json", success: function (response) { alert(response.d); } });
Lato server .ashx
using System; using System.Web; using Newtonsoft.Json; public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string myName = context.Request.Form["firstName"]; // simulate Microsoft XSS protection var wrapper = new { d = myName }; context.Response.Write(JsonConvert.SerializeObject(wrapper)); } public bool IsReusable { get { return false; } } }
Se si inviano dati al server con riferimento a $.ajax
i dati non verranno convertiti automaticamente in dati JSON (vedere Come si costruisce un object JSON da inviare a un servizio Web AJAX? ). Quindi puoi usare contentType: "application/json; charset=utf-8"
e dataType: "json"
e rimanere non convertire i dati con JSON.stringify
o $.toJSON
. Invece di
data: "{'file':'dave', 'type':'ward'}"
(conversione manuale dei dati in JSON) puoi provare a utilizzarli
data: {file:'dave', type:'ward'}
e ottenere i dati sul lato server con i costrutti context.Request.QueryString["file"]
e context.Request.QueryString["type"]
. Se ricevi qualche problema in questo modo, puoi provare con
data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}
e utilizzare DataContractJsonSerializer
sul lato server.
html js (function($) { $(document).ready(function() { $('#getReport').click(function(e) { e.preventDefault(); window.location = 'pathtohandler/reporthandler.ashx?from={0}&to={1}'.f('01.01.0001', '30.30.3030'); }); }); // string format, like C# String.prototype.format = String.prototype.f = function() { var str = this; for (var i = 0; i < arguments.length; i++) { var reg = new RegExp('\\{' + i + '\\}', 'gm'); str = str.replace(reg, arguments[i]); } return str; }; })(jQuery); c# public class ReportHandler : IHttpHandler { private const string ReportTemplateName = "report_template.xlsx"; private const string ReportName = "report.xlsx"; public void ProcessRequest(HttpContext context) { using (var slDocument = new SLDocument(string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~"), ReportTemplateName))) { context.Response.Clear(); context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", ReportName)); try { DateTime from; if (!DateTime.TryParse(context.Request.Params["from"], out from)) throw new Exception(); DateTime to; if (!DateTime.TryParse(context.Request.Params["to"], out to)) throw new Exception(); ReportService.FillReport(slDocument, from, to); slDocument.SaveAs(context.Response.OutputStream); } catch (Exception ex) { throw new Exception(ex.Message); } finally { context.Response.End(); } } } public bool IsReusable { get { return false; } } }
Questo funziona per chiamare i servizi Web. Non sono sicuro di .ASHX
$.ajax({ type: "POST", url: "/test.asmx/SomeWebMethodName", data: {'file':'dave', 'type':'ward'}, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { $('#Status').html(msg.d); }, error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert('Error: ' + err.Message); } }); [WebMethod] public string SomeWebMethodName(string file, string type) { // do something return "some status message"; }
è necessario definire le proprietà del gestore nel file di configurazione Web per gestire i formati di richiesta di estensione definiti dall’utente. qui l’estensione definita dall’utente è ” .api”
aggiungi verb = “*” percorso = “test.api” type = “test” sostituire l’ url: “/test.ashx” in url: “/test.api” .
se si usa $ .ajax e si usa .ashx per ottenere querystring, non impostare datatype
$.ajax({ type: "POST", url: "/test.ashx", data: {'file':'dave', 'type':'ward'}, **//contentType: "application/json; charset=utf-8", //dataType: "json"** });
lo faccio funzionare!
Prova System.Web.Script.Serialization.JavaScriptSerializer
Con la trasmissione al dizionario