I'm trying to pass JSON from jQuery to a .ASHX file. Example of the jQuery below:
$.ajax({
type: "POST",
url: "/test.ashx",
data: "{'file':'dave', 'type':'ward'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
How do I retrieve the JSON data in my .ASHX file? I have the method:
public void ProcessRequest(HttpContext context)
but I can't find the JSON values in the request.
I know this is too old, but just for the record I'd like to add my 5 cents
You can read the JSON object on the server with this
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
The following solution worked for me:
Client Side:
$.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);
}
});
Server Side .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;
}
}
}
If you send data to the server with respect of $.ajax
the data will not be converted to JSON data automatically (see How do I build a JSON object to send to an AJAX WebService?). So you can use contentType: "application/json; charset=utf-8"
and dataType: "json"
and stay don't convert data with JSON.stringify
or $.toJSON
. Instead of
data: "{'file':'dave', 'type':'ward'}"
(manual converting of data to JSON) you can try use
data: {file:'dave', type:'ward'}
and get the data on the server side with context.Request.QueryString["file"]
and context.Request.QueryString["type"]
constructs. If you do receive some problems with this way then you could try with
data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}
and usage DataContractJsonSerializer
on the server side.
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; } }
}
This works for calling web services. Not sure about .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";
}
you have to defined the handler properties in web configuration file to handle the user defined extension request formats. here the user defined extension is ".api"
add verb="*" path="test.api" type="test" replace the url: "/test.ashx" to url: "/test.api" .
if using $.ajax and using .ashx to get querystring ,dont set datatype
$.ajax({
type: "POST",
url: "/test.ashx",
data: {'file':'dave', 'type':'ward'},
**//contentType: "application/json; charset=utf-8",
//dataType: "json"**
});
i get it work!
Try System.Web.Script.Serialization.JavaScriptSerializer
With casting to dictionary
来源:https://stackoverflow.com/questions/2948628/asp-net-passing-json-from-jquery-to-ashx