【问题标题】:WebMethod In Aspx Page Can Not Have access Allow-OriginAspx 页面中的 WebMethod 无法访问 Allow-Origin
【发布时间】:2013-07-03 08:34:18
【问题描述】:

我有以下代码。它不能用于启用 CORS。请帮助。我无法在我的 Web 方法中在 aspx 页面上启用 CORS:

public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.AppendHeader("Access-Control-Allow-Origin", "*");
            Response.AppendHeader("access-control-allow-headers", "content-type");
        }

        [WebMethod]
        [ScriptMethod] 
        public static string Get(string data)
        {
            System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            System.Web.HttpContext.Current.Response.AppendHeader("access-control-allow-headers", "content-type");
            return data + " 123";
        }

    }

    // Java Script


    function GetData() {
    window.jQuery.support.cors = true;
    window.jQuery.ajax({
        url: 'http://generalservices.prop.preview.gearhost.com//Default.aspx/Get',

        contentType: "application/json; charset=utf-8",
        dataType: "json",
        type: 'post',
        data: "{ data : '12'}",
        success: function (d) {

        },
        error: function (d) {

        }
    });

错误:在 Access-Control-Allow-Origin 中不允许

【问题讨论】:

    标签: asp.net ajax webmethod


    【解决方案1】:

    页面方法应该只在定义它们的同一页面中使用。

    如果您需要从不同页面获取数据,我建议您查看Asp.Net Web api。或者你甚至可以创建一个简单的Generic handler.ashx 文件),你可以从你的页面调用它。处理程序可以反序列化 Json 数据,对其进行处理并返回所需的响应。在通用处理程序中,您可以指定所需的任何/所有 http 标头。

    【讨论】:

    • 感谢推荐,但这是旧版本代码,我们不想更改它
    • 通用处理程序自 Asp.Net 版本 1 以来就已经存在。
    猜你喜欢
    • 2016-01-04
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多