繁体   English   中英

ASP.NET Web API会话数据

[英]ASP.NET Web API Session Data

我需要在Web API项目中的Session Data中存储一个大对象。 然后我需要,客户端上的一些HTML小部件想要在Web API的会话中访问该数据,并使用它做不同的事情,比如绘制数据的图表小部件,列出数据的HTML表。 我不需要为每个客户端窗口小部件重新计算大型对象,而是需要将其计算为ONCE并将其存储在会话数据中,以便在同一会话中的客户端上运行的任何窗口小部件都可以在会话中的不同时间访问该数据而不必等待服务器重新计算数据。

每个小部件都应使用不同的GET请求URL访问Web API服务器项目。

我很感激帮助。 我可能已经对如何做到这一点进行了高级概述,但我可以使用一些指导。

这是你如何做到的。

您可以在项目中使用Repository(Repository Pattern),在Repository中,您可以使用计算小部件所需结果的方法等。在Repository方法中定义数据计算的所有逻辑,然后在apiController中获取Get Request或GetById调用该存储库并可以创建一个可在View中使用的会话变量。如果您使用Asp.Net Mvc作为前端,您可以执行相同的调用,将数据存储到Mvc控制器内的会话中

public class YourControllerName:apiController
{
    public IQueryable<AnyNameListDTO> Get()
    {
        //Your other Code will go here 
        var session = HttpContext.Current.Session;
        if (session != null)
        {
            if (session["AnyName"] == null)
            {
                session["AnyName"] = TheRepository.YourMethodName();
            }
        }
    }
}

如果您使用Asp.Net Mvc作为将使用Web Api的视图(UI),那么您可以在控制器内创建相同的会话。

public class YourControllerName:Controller
{
    public ActionResult Get()
    {
        //Your other Code will go here 
        Session["AnyName"] = TheRepository.YourMethodName();
    }
}   

您也可以使用HTML5本地存储。

利用HTML5本地存储存储数据,然后使用它。

解决了

从跨域.html页面检索Web API会话数据

跨域资源共享就是这样

ValuesController.cs Web API中)

namespace TestWEB_API.Controllers
{
  public class ValuesController : ApiController
  {

    // GET api/values
    public string Get()
    {
        var session = HttpContext.Current.Session;
        if (session != null)
        {
            if (session["Time"] == null)
                session["Time"] = DateTime.Now;
            return "Session Time: " + session["Time"];
        }
        return "Session is not working";
    }// End Get()

    ...

  }//End Class()
}//End Namespace

然后.html页面( 不在 WEB API !!!)在另一个.war

httpSessionTest.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

    <script type="text/javascript" src="../Desktop/jquery-2.1.1.js"></script>

</head>
<script>
// !!------------- THIS IS WHAT I NEEDED! ---------------!!
$(function()
{
        $.getJSON('http://localhost:Port/api/values', function(stringPayLoad)
        {
            alert(stringPayLoad);
            $("#dataP").text(stringPayLoad);
        });
});

</script>
<body>
<h3> Web API Session Test </h3>
<p id="dataP">!!! If you see this, it means that the session data didn't load. :(</p>

</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM