将 JSON 发布到 ASP.NET Web 服务 (ASMX) 仅达到 OPTION 而不是完整的 POST

发布于 2025-01-03 21:31:22 字数 3431 浏览 0 评论 0原文

我一直在开发一个 JQuery 脚本,它将 JSON 发布到我的 asp.net Web 服务。如果脚本位于同一个域上,它会正确处理,但是当我尝试从本地文件或替代域上运行脚本时,眼睛似乎不会发生这种情况!...尽管我注意到,在我的网络日志中,尝试到达服务器,但使用方法 OPTIONS 而不是 POST。

我尝试直接在 IIS、web.config 和我的 global.asax 文件中将以下标头设置为 application_beginRequest 事件,但到目前为止没有成功!

访问控制允许来源 *

访问控制允许方法 GET、POST。

我的 global.asax 文件包含以下内容:

protected void Application_BeginRequest(object sender, EventArgs e)
{

    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Current.Response.Cache.SetNoStore();

    EnableCrossDmainAjaxCall();
}

private void EnableCrossDmainAjaxCall()
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                      "GET, POST, OPTIONS");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                      "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                      "1728000");
        HttpContext.Current.Response.End();
    }
}

我的客户端脚本如下:

$.ajax({
            type: "POST",
            crossDomain: true,
            url: "http://myservice.mydomain.com/Data.asmx/Import",
            data: "{\"AppSession\":" + JSON.stringify(session) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                // Insert the returned HTML into the <div>.
                $('#content').html(data.d);
            },
            error: function (j, t, e) {

                $('#content').html(e);
            }
        });

我的 Web 服务代码如下...

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

/// <summary>
/// Summary description for DataMgt
/// </summary>
[WebService(Namespace = "DataManagement")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]

public class DataMgt : System.Web.Services.WebService {

    public DataMgt () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 

    }
    public class GeoData
    {
        public string GEOLongitude { get; set; }
        public string GEOLatitude { get; set; }
        public string GEOAccuracy { get; set; }
        public string GEOStatusID { get; set; }
    }

    public class AppSession
    {
        public GeoData GEOData { get; set; }
        public string UserID { get; set; }
        public string CountryID { get; set; }
    }

    [WebMethod]

    public string ImportData(AppSession AppSession)
    {
        string strStatusCode;
        try
        {
            //Do stuff here with requested data

            strStatusCode = "SUCCESS";
        }
        catch (Exception ex)
        {
            strStatusCode = "FAILURE";
        }

        return strStatusCode;

    } 
}

正如我之前所说,当客户端脚本在同一域上运行时,这绝对可以正常运行。

托管我的服务的网站位于 IIS 7 和 ASP.NET 4 上。

是否有人在使用与我类似的设置时遇到过此问题,或者有人可以建议如何解决此问题?

预先非常感谢,

瑞特

I have been working on a JQuery script that posts JSON to my asp.net web service. If the script is on the same domain it processes correctly but when I try to run the script from a local file or on an alternative domain not appears to happen to the eye!.. Though what I have noticed is that within my web logs the attempt is reaching the server but with the method OPTIONS rather than POST.

I have tried to set the following headers within IIS, web.config directly and within my global.asax file to on the application_beginRequest event but no success thus far!

Access-Control-Allow-Origin *

Access-Control-Allow-Methods GET, POST.

My global.asax file contain this:

protected void Application_BeginRequest(object sender, EventArgs e)
{

    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Current.Response.Cache.SetNoStore();

    EnableCrossDmainAjaxCall();
}

private void EnableCrossDmainAjaxCall()
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                      "GET, POST, OPTIONS");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                      "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                      "1728000");
        HttpContext.Current.Response.End();
    }
}

My client side script is as follows:

$.ajax({
            type: "POST",
            crossDomain: true,
            url: "http://myservice.mydomain.com/Data.asmx/Import",
            data: "{\"AppSession\":" + JSON.stringify(session) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                // Insert the returned HTML into the <div>.
                $('#content').html(data.d);
            },
            error: function (j, t, e) {

                $('#content').html(e);
            }
        });

My web service code is as follows...

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

/// <summary>
/// Summary description for DataMgt
/// </summary>
[WebService(Namespace = "DataManagement")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]

public class DataMgt : System.Web.Services.WebService {

    public DataMgt () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 

    }
    public class GeoData
    {
        public string GEOLongitude { get; set; }
        public string GEOLatitude { get; set; }
        public string GEOAccuracy { get; set; }
        public string GEOStatusID { get; set; }
    }

    public class AppSession
    {
        public GeoData GEOData { get; set; }
        public string UserID { get; set; }
        public string CountryID { get; set; }
    }

    [WebMethod]

    public string ImportData(AppSession AppSession)
    {
        string strStatusCode;
        try
        {
            //Do stuff here with requested data

            strStatusCode = "SUCCESS";
        }
        catch (Exception ex)
        {
            strStatusCode = "FAILURE";
        }

        return strStatusCode;

    } 
}

As I said earlier, this runs absolutely fine when the client side script is run on the same domain.

The website that hosts my service is on IIS 7 and ASP.NET 4.

Has anyone expereinced this when using a similar setup to me or can anyone suggest how to resolve this?

Many thanks in advance,

Rit

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

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

发布评论

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

评论(3

弄潮 2025-01-10 21:31:22

如果您在不同的域上工作,您将无法向您的服务器发送 POST 请求。它的限制,你必须使用 JSONP

JSONP:
http://api.jquery.com/jQuery.getJSON/

教程:
http://abstractform。 wordpress.com/2009/10/12/accessing-remote-asp-net-web-services-using-jsonp/

If you working on diffrent domain you will not be able to POST request to your server. Its restricted, you have to use JSONP

JSONP:
http://api.jquery.com/jQuery.getJSON/

A tutorial:
http://abstractform.wordpress.com/2009/10/12/accessing-remote-asp-net-web-services-using-jsonp/

难如初 2025-01-10 21:31:22

我不知道是否这么简单,但是当我尝试使用 jQuery 进行跨域 .ajax() 调用时,我必须将其附加到 url 中:

&jsoncallback=?

I don't know if it's this simple, but when I try to make a cross domain .ajax() call with jQuery I have to append this to the url:

&jsoncallback=?
娇柔作态 2025-01-10 21:31:22

您需要使用 jsonp 而不是 json 的数据类型。检查 jQuery 文档中的 ajax 方法。

You need to use a dataType of jsonp rather than json. Check the jQuery docs for the ajax method.

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