无法在Httpcontext.Current.Session中设置数据

时间:2017-07-18 08:16:22

标签: c# session httpcontext

我是WebApi的初学者,尝试访问全局容器以保存和存储用户的数据,但无法确定数据在会话中存储的内容和原因,请请参阅下面的代码:

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        protected void Application_PostAuthorizeRequest()
        {
            System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }
        private bool IsWebApiRequest()
        {
            var appRelative = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath != null;
            var urlPrefix = appRelative && HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
            return urlPrefix;
        }
        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            // Session is Available here
            if (HttpContext.Current.Session != null)
             {
                 if (HttpContext.Current.Session["con"] == null)
                 {
                     HttpContext.Current.Session["con"] = "Sample";
                 }
             }
        }
    }

的Global.asax.cs

public class SampleController : ApiController
{
    [System.Web.Http.Route("setsession"),HttpGet]
    //api/v1/sample/setsession/
    public IHttpActionResult SetSession()
    {
        var con = (string)HttpContext.Current.Session["con"];
        HttpContext.Current.Session["con"]= "Hello World";
        con = (string)HttpContext.Current.Session["con"];
        return Ok();
    }

    [System.Web.Http.Route("getsession"), HttpGet]
    //api/v1/sample/getsession/
    public IHttpActionResult GetSession()
    {
        var data = (string)HttpContext.Current.Session["con"];
        return Ok();
    }
}

SampleController.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();
        var constraintsResolver = new DefaultInlineConstraintResolver();
        constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
        config.MapHttpAttributeRoutes(constraintsResolver);
        config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
        config.Formatters.RemoveAt(0);
        config.Formatters.Insert(0, new SecureJsonMediaTypeFormatter());

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        // Ignoring circular reference globally
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        // Preserving circular reference globally
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
        config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

        // Remove the JSON formatter
        //config.Formatters.Remove(config.Formatters.JsonFormatter);

        // Remove the XML formatter
        config.Formatters.Remove(config.Formatters.XmlFormatter);
    }
}

WebApiConfig.cs

如您所见,我将HttpContext.Current.Session["con"]设置为默认值Sample,让我知道有值。该场景是当我将值api/v1/sample/setsession设置为Session["con"]时,结果完全正常,"Hello World"传递给Session["con"]。但当我"api/v1/sample/getsession" global.asax.cs成功且HttpContext.Current.Session["con"] = null or no value中的条件,并且不知道为什么会发生这种情况时,我也会设置sessionState mode="InProc",其中存储会话状态Web服务器上的内存,但仍然会话转为默认,没有数据存储,请帮助,任何评论将被评论,提前谢谢。

0 个答案:

没有答案