Request.Cookies总是通过jQuery Ajax调用返回null

时间:2014-11-09 06:22:05

标签: jquery cookies asp.net-ajax

我有jQuery Ajax调用,它在服务器端设置cookie。如果cookie存在,它应该将值附加到cookie。这里的问题是,当从Ajax调用调用时,HttpContext.Current.Request.Cookies总是返回null(虽然cookie存在于浏览器中)。

这种情况正在发生,因为HttpContext.Current.Request.Cookies在Ajax请求URL /页面而不是父页面中进行搜索。

如何从原始页面获取Cookie?任何的想法?

Ajax电话:

 function GccVideos (http,gccCookieJar,captain) {
    var watchedVideos = [];
    var path = captain.path();

    init();

    this.watch = function (vguid) {
          var request = {
          method: 'POST',
          url: '/videos/watched',
          data: {
             VideoGuid: vguid
          }
        };
        http(request)
          .success(function(response){
            console.log('GccVideos.watched('+vguid+'): Success: ',response);
          })
          .error(function(error){
            throw new Error('GccVideos.watch('+vguid+'): '+error);
          })
        ;
      }

服务器端代码:

[Route("videos/watched")]
public void SetVideoWatched()
    {
         HttpCookie videoRotationCookie = HttpContext.Current.Request.Cookies[_config.VideoRotation.CookieName] ??
                                                new HttpCookie(_config.VideoRotation.CookieName);

       var videoItem =  _contentItemService.GetItem<VideoItem>(key);

        var videoNameValueCollection = new NameValueCollection { { videoItem.AnalyticsVideoName , videoItem.Key.ToString() } };

        if (videoRotationCookie.Values.AllKeys.Contains(videoItem.AnalyticsVideoName))
        {
            videoRotationCookie.Values.Remove(videoItem.AnalyticsVideoName);
        }

        videoRotationCookie.Path = HttpContext.Current.Request.UrlReferrer.AbsolutePath;

        videoRotationCookie.Expires = DateTime.Now.AddDays(_config.VideoRotation.Duration);

        videoRotationCookie.Values.Add(videoNameValueCollection);

        HttpContext.Current.Response.Cookies.Add(videoRotationCookie);
    }

0 个答案:

没有答案