ASP.NET -passage de JSON de jQuery à ASHX

j'essaie de passer JSON de jQuery à A.ASHX fichier. Exemple de jQuery ci-dessous:

$.ajax({
      type: "POST",
      url: "/test.ashx",
      data: "{'file':'dave', 'type':'ward'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",      
    });

Comment puis-je récupérer les données JSON dans mon .ASHX fichier? J'ai la méthode:

public void ProcessRequest(HttpContext context)

mais je ne trouve pas les valeurs JSON dans la requête.

42
demandé sur Majid 2010-06-01 13:35:18

8 réponses

je sais que c'est trop vieux, mais juste pour information j'aimerais ajouter mes 5 cents

vous pouvez lire l'objet JSON sur le serveur avec ce

string json = new StreamReader(context.Request.InputStream).ReadToEnd();
55
répondu Claudio Redi 2014-06-12 21:46:47

la solution suivante a fonctionné pour moi:

Côté Client:

        $.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);
            }
        });

Côté Serveur .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;
           }
        }
    }
24
répondu Andre 2011-07-08 18:55:33

si vous envoyez des données au serveur en ce qui concerne $.ajax les données ne seront pas converties en données JSON automatiquement (voir Comment puis-je construire un objet JSON pour l'Envoyer à un service Web AJAX? ). Vous pouvez donc utiliser contentType: "application/json; charset=utf-8" et dataType: "json" et rester ne pas Convertir les données avec JSON.stringify ou $.toJSON . Au lieu de

data: "{'file':'dave', 'type':'ward'}"

(conversion manuelle des données en JSON) vous pouvez essayer d'utiliser

data: {file:'dave', type:'ward'}

et obtenez les données du côté du serveur avec les constructions context.Request.QueryString["file"] et context.Request.QueryString["type"] . Si vous recevez quelques problèmes de cette façon, alors vous pourriez essayer avec

data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}

et utilisation DataContractJsonSerializer du côté serveur.

4
répondu Oleg 2017-05-23 11:47:12
html
<input id="getReport" type="button" value="Save report" />

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; } }
}
2
répondu oyaebunterkrah 2013-09-12 09:44:40

cela fonctionne pour appeler des services web. Ce n'est pas sûr .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";
}
1
répondu Larry Flewwelling 2010-09-20 20:10:37

vous devez définir les propriétés du gestionnaire dans le fichier de configuration web pour gérer les formats de requête d'extension définis par l'utilisateur. ici, l'extension définie par l'utilisateur est" ".api "

ajouter verbe="*"path=" test.api"type=" test " remplacer url: "/ test.ashx" à url: "/test.api " .

0
répondu Ashish Sharma 2010-09-21 12:16:46

si vous utilisez $.ajax et utilisation .ashx pour obtenir querystring ,ne mettez pas de type de données

$.ajax({ 
    type: "POST", 
    url: "/test.ashx", 
    data: {'file':'dave', 'type':'ward'}, 
    **//contentType: "application/json; charset=utf-8",   
    //dataType: "json"**    
}); 

je le faire fonctionner!

-1
répondu user411861 2010-09-13 19:53:11

Essayer System.Web.Script.Serialization.JavaScriptSerializer

avec moulage au dictionnaire

-4
répondu Dewfy 2015-10-19 23:37:58