ASP.NET - 将 JSON 从 jQuery 传递到 ASHX

发布于 2024-09-04 10:29:41 字数 411 浏览 4 评论 0原文

我正在尝试将 JSON 从 jQuery 传递到 .ASHX 文件。下面的 jQuery 示例:

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

如何检索 .ASHX 文件中的 JSON 数据?我有方法:

public void ProcessRequest(HttpContext context)

但我找不到请求中的 JSON 值。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

匿名。 2024-09-11 10:29:41

我知道这太旧了,但只是为了记录我想添加我的 5 美分

你可以用这个读取服务器上的 JSON 对象

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

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();
梦回旧景 2024-09-11 10:29:41

以下解决方案对我有用:

客户端:

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

服务器端.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;
           }
        }
    }

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;
           }
        }
    }
心凉 2024-09-11 10:29:41

如果您向服务器发送关于 $.ajax 的数据,则数据不会自动转换为 JSON 数据(请参阅 如何构建 JSON 对象以发送到 AJAX WebService?)。因此,您可以使用 contentType: "application/json; charset=utf-8"dataType: "json" 并且不要使用 JSON 转换数据。 stringify$.toJSON。 而不是

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

(手动将数据转换为 JSON)

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

您可以尝试使用context.Request.QueryString["file"] 和 context.Request.QueryString[ 在服务器端获取数据, “类型”] 构造。如果您确实以这种方式遇到一些问题,那么您可以尝试

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

在服务器端使用 DataContractJsonSerializer

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.

同尘 2024-09-11 10:29:41
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; } }
}
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; } }
}
始终不够 2024-09-11 10:29:41

这适用于调用网络服务。不确定 .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";
}

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";
}
空袭的梦i 2024-09-11 10:29:41

您必须在 Web 配置文件中定义处理程序属性来处理用户定义的扩展请求格式。这里用户定义的扩展名是“.api”

add verb="*" path="test.api" type="test"
url: "/test.ashx" 替换为 url: "/test.api"

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" .

忆离笙 2024-09-11 10:29:41

如果使用 $.ajax 并使用 .ashx 获取查询字符串,不要设置数据类型,

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

我可以正常工作!

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!

千鲤 2024-09-11 10:29:41

尝试使用 System.Web.Script.Serialization.JavaScriptSerializer

强制转换为字典

Try System.Web.Script.Serialization.JavaScriptSerializer

With casting to dictionary

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文