如何使用头请求将参数从Ajax传递到C#?

时间:2012-07-01 12:05:50

标签: c# ajax header

我有以下要求:

var response = $.ajax({
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    url: this.AgentServiceUrl + "/" + methodName,
    data: data,
    async: this.Async,
    success: function (xml, textStatus) { if (successHandler != null) successHandler(state, $.xml2json(xml), textStatus); },
    error: function (xmlHttpRequest, textStatus, errorThrown) { if (errorHandler != null) errorHandler(state, xmlHttpRequest, textStatus, errorThrown); }
});

我想在此请求标头中添加一个变量,并在C#,

上使用它

我尝试了很多方法,但我不能在C#上使用它:

  1.  beforeSend: function (req)  
     {  
         req.setRequestHeader("AgentGUID", this.AgentGUID);  
     },
    
  2. 通过parameters:

  3. 你能帮帮我吗?我不想改变C#部分的功能,我只想使用类似的东西:

    (System.Web.HttpContext.Current.Request.Headers["someHeader"]
    

1 个答案:

答案 0 :(得分:4)

您的beforeSend应该可以正常工作,但是您在服务器端无法获得价值的原因是此方法调用this.AgentGUIDundefined,因为this在该上下文中指向另一个对象(最可能是ajax请求对象)。

通过在ajax调用之外定义变量,您的问题将得到解决。

var me = this;
var response = $.ajax({
    ...
    beforeSend: function (req)
    {
        req.setRequestHeader("AgentGUID", me.AgentGUID);
    },
    ...
});