2010-06-01 26 views
40

Estoy tratando de pasar JSON de jQuery a un archivo .ASHX. Ejemplo de jQuery a continuación:ASP.NET - Pasando JSON de jQuery a ASHX

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

¿Cómo recupero los datos JSON en mi archivo .ASHX? Tengo el método:

public void ProcessRequest(HttpContext context) 

pero no puedo encontrar los valores JSON en la solicitud.

+0

la muestra va a ayudarle a http://stackoverflow.com/a/19824240/1153856 – OsmZnn

Respuesta

-3

Trate System.Web.Script.Serialization.JavaScriptSerializer

con la fundición al diccionario

+2

Gracias por la respuesta. ¿Podrías elaborar un poco por favor? ¿Qué objeto debería serializar? –

+0

@colin, prefiero Dictionary, pero puede persistir cualquier objeto, por ejemplo en su ejemplo: class MyObj {public String file, type; } – Dewfy

4

Si envía los datos al servidor con respecto a $.ajax los datos no se convierten en datos JSON de forma automática (ver How do I build a JSON object to send to an AJAX WebService?). Para que pueda usar contentType: "application/json; charset=utf-8" y dataType: "json" y quedarse, no convierta datos con JSON.stringify o $.toJSON. En lugar de

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

(manual de la conversión de los datos a JSON), puede intentar utilizar

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

y obtener los datos en el lado del servidor con context.Request.QueryString["file"] y context.Request.QueryString["type"] construcciones. Si recibe algunos problemas con esta manera entonces se podría tratar con

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

y el uso DataContractJsonSerializer en el lado del servidor.

+0

Gracias por la respuesta. El problema que estoy teniendo es que no puedo obtener los datos JSON en el objeto de solicitud cuando uso una página ASHX. El valor de context.Request.QueryString ["file"] siempre es nulo. ¿Sabrías cómo obtener los datos JSON en la solicitud? –

+0

Para poder ver el parámetro 'file' con' context.Request.QueryString ["file"] 'debe usar' data' como 'data: {file: 'dave', type: 'ward'}' (vea mi responder). Luego se definirán los parámetros de consulta con los nombres 'file' y' type' y los datos enviados al servidor se codificarán como 'file = dave? Type = ward'. – Oleg

+2

Si su AJAX está realizando una POST, los datos estarán en la propiedad Request.Form, no en QueryString. –

-1

si se usa $ .ajax y el uso de .ashx para obtener cadena de consulta, no te establecer el tipo de datos

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

consigo que funcione!

1

Esto funciona para llamar a servicios web. No estoy seguro sobre .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"; 
} 
0

tienes que definen las propiedades de controlador en el archivo de configuración web para manejar los formatos de solicitud de extensión definidas por el usuario. aquí la extensión definida por el usuario es ".api"

añadir verbo = "*" path = tipo "test.api" = "prueba" sustituir el url: "/test.ashx" a url: "/test.api".

23

La siguiente solución funcionó para mí:

lado 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); 
      } 
     }); 

el lado del servidor.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; 
      } 
     } 
    } 
+0

No funcionó para mí de esta manera, sino más bien: 'string myName = context.Request [" firstName "]'; – Jaanus

+0

@Jaanus ¿Estás usando POST? – Andre

+0

@Andre puedo obtener {firstName: 'stack', lastName: 'overflow'} Full String. No necesito separarme. Proporcione una solución http://stackoverflow.com/questions/24732952/receive-the-jsonquery-string-in-webmethod?noredirect=1#comment38367134_24732952 – Sagotharan

49

Sé que esto es demasiado viejo, pero sólo para el registro me gustaría añadir mis 5 centavos

Puede leer el objeto JSON en el servidor con este

string json = new StreamReader(context.Request.InputStream).ReadToEnd(); 
+0

Esta es la forma correcta de hacerlo funcionar. Perfecto. –

+0

este es el 5 centavos más importante. Me gustaría agregar algo si no te importa. – naveen

+0

@ Claudio Redi Ayúdenme a resolver esto ... http://stackoverflow.com/questions/24732952/receive-the-jsonquery-string-in-webmethod?noredirect=1#comment38367134_24732952 – Sagotharan

2
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; } } 
} 
Cuestiones relacionadas