www.91084.com

GVKun编程网logo

asp.net-mvc – asp.net mvc在控制器构建期间的任何时候都可以使用Session吗?

20

如果您想了解asp.net-mvc–asp.netmvc在控制器构建期间的任何时候都可以使用Session吗?的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于ASP.NETMVC在基控制器

如果您想了解asp.net-mvc – asp.net mvc在控制器构建期间的任何时候都可以使用Session吗?的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于ASP.NET MVC在基控制器中处理Session、asp.net-core-mvc – 如何在Asp.Net Core MVC 1.0(又名MVC 6 RC1)中访问Session Timeout值?、asp.net-mvc – ASP.NET MVC 3 – 这个布尔值如何在控制器中运行?、asp.net-mvc – ASP.NET mvc 4控制器参数始终为空时发送json到控制器,为什么?的有价值的信息。

本文目录一览:

asp.net-mvc – asp.net mvc在控制器构建期间的任何时候都可以使用Session吗?

asp.net-mvc – asp.net mvc在控制器构建期间的任何时候都可以使用Session吗?

我试图在控制器和ControllerContext的构造函数中访问Session变量,它似乎总是为null.

最早的会话变量何时可用?

谢谢!

编辑:示例:

在一个控制器中:

public HomeController()
    {
        MyClass test =   (MyClass)ControllerContext.HttpContext.Session["SessionClass"];
    //ControllerContext always null           
    }

在调试时,controllercontext始终为null.在actionresult重定向到此控制器的控制器中,我有:

Session["SessionClass"] = class;

MyClass test = (MyClass )ControllerContext.HttpContext.Session["SessionClass"]; 
// this works fine! i can get varibale from session

return RedirectToAction("Index","Home");

那么,ControllerContext在什么时候实际设置?我什么时候可以访问会话变量?

解决方法

覆盖 Initialize():

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    requestContext.HttpContext.Session["blabla"] = "hello"; // do your stuff
}

ASP.NET MVC在基控制器中处理Session

ASP.NET MVC在基控制器中处理Session

当需要跨页面共享信息的时候,Session是首当其冲的选择,最典型的例子就是:在处理登录和购物车逻辑的时候需要用到Session。在MVC中,可以把处理Session的逻辑放在一个泛型基控制器中,但需要注意的是:在判断没有登录就跳转到登录页的时候,需要把出错控制器和登录控制器排除在外。

using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1.Controllers
{
    public class BaseController<TModel> : Controller
    {

        private const string loginSession = "LoginSession";
        private const string shoppingCartSession = "ShoppingCartSession";
        private const string errorController = "Error";
        private const string LoginController = "Login";
        private const string LoginAction = "Login";

        //没有登录的跳转到登录页
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            //如果没有登录,且不是出错和登录控制器就跳转到登录页
            if (!NoNeedSessionController(requestContext) && !HasLoginSession())
            {
                GoToAction(requestContext, Url.Action(LoginAction, LoginController));
            }
        }

        //对哪些不需要依赖缓存的控制器 返回true
        private bool NoNeedSessionController(RequestContext requestContext)
        {
            //从路由数据中取到当前controller的名称
            var c = requestContext.RouteData.Values["controller"].ToString().ToLower();

            //把不需要依赖Session的控制器名称放到列表中
            var noNeedSessionList = new List<string>
            {
                errorController.ToLower(),
                LoginController.ToLower()
            };

            return noNeedSessionList.Contains(c);
        }

        //跳转到某个视图
        private void GoToAction(RequestContext requestContext, string action)
        {
            requestContext.HttpContext.Response.Clear();
            requestContext.HttpContext.Response.Redirect(action);
            requestContext.HttpContext.Response.End();
        }

        //登录的时候判断是否有Session
        protected bool HasLoginSession()
        {
            return Session[loginSession] != null;
        }

        //判断购物车是否有Session
        protected bool HasShoppingCartSession()
        {
            return Session[shoppingCartSession] != null;
        }

        //从Session中获取登录模型的实例
        protected TModel GetLoginModelFromSession()
        {
            return (TModel)this.Session[loginSession];
        }

        //从Session中获取购物车模型的实例
        protected TModel GetShoppingCartModelFromSession()
        {
            return (TModel)this.Session[shoppingCartSession];
        }

        //设置登录Session
        protected void SetLoginSession(TModel loginModel)
        {
            Session[loginSession] = loginModel;
        }

        //设置购物车Session
        protected void SetShoppingCartSession(TModel shoppingCartModel)
        {
            Session[shoppingCartSession] = shoppingCartModel;
        }

        //让登录Session失效
        protected void AbandonLoginSession()
        {
            if (HasLoginSession())
            {
                Session.Abandon();
            }
        }

        //让购物车Session失效
        protected void AbandonShoppingCartSession()
        {
            if (HasShoppingCartSession())
            {
                Session.Abandon();
            }
        }
    }
}

让其他控制器派生于基控制器:

using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class LoginController : BaseController<LoginModel>
    {
        public ActionResult Index()
        {
            //把登录模型实例保存到Session中
            LoginModel loginModel = new LoginModel();
            SetLoginSession(loginModel);

            //从Session中获取登录模型实例
            LoginModel sessioModel = GetLoginModelFromSession();

            //使登录Session失效
            AbandonLoginSession();
            return View();
        }

    }
}

到此这篇关于ASP.NET MVC在基控制器中处理Session的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • 如何在ASP.NET Core中使用Session的示例代码
  • 如何解决asp.net负载均衡时Session共享的问题
  • Asp.Net Core中基于Session的身份验证的实现
  • 浅谈ASP.NET Core中间件实现分布式 Session
  • 解析Asp.net Core中使用Session的方法
  • asp.net(C#)清除全部Session与单个Session的方法
  • 详解ASP.NET中Session的用法
  • ASP.NET ASHX中获得Session的方法
  • ASP.NET将Session保存到数据库中的方法
  • asp.net session的使用与过期实例代码
  • Asp.net中判断一个session是否合法的方法

asp.net-core-mvc – 如何在Asp.Net Core MVC 1.0(又名MVC 6 RC1)中访问Session Timeout值?

asp.net-core-mvc – 如何在Asp.Net Core MVC 1.0(又名MVC 6 RC1)中访问Session Timeout值?

在Asp.Net Core MVC 1.0(MVC 6 RC1)中,在Startup.cs中的ConfigureServices方法中添加会话支持时指定会话超时期限,如下所示:
services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.CookieName = "Session";
        });

我的问题是:在应用程序的其他地方,如何访问此IdleTimeout值?

我希望从HttpContext.Session对象中找到它作为属性,但它似乎并不存在.我搜索过高低,这似乎没有记录在任何地方.思考?

解决方法

这似乎是 DistributedSession类中的私有字段.所以目前,你无法得到它. Session似乎缺少旧版 HttpSessionState课程中的很多属性,但我找不到任何指向原因的东西(可能有一个好的!).

你可以用反射得到它,但它非常粗糙.以下示例使用this answer.

public IActionResult Index()
{
    var value = GetInstanceField(typeof(distributedSession),HttpContext.Session,"_idleTimeout");
    return View();
}

我建议将值存储在配置文件或某个内部类中.

asp.net-mvc – ASP.NET MVC 3 – 这个布尔值如何在控制器中运行?

asp.net-mvc – ASP.NET MVC 3 – 这个布尔值如何在控制器中运行?

我在asp网站上看到asp.net mvc的教程: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

控制器中有一种让我困惑的方法:

//
        // GET: /Student/Delete/5

        public ActionResult Delete(int id,bool? saveChangesError)
        {
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Unable to save changes.  Try again,and if the problem persists contact your system administrator.";
            }
            return View(db.Students.Find(id));
        }

我看到创建了一个名为’saveChangesError’的bool,但在if语句中,有一个方法被调用在名为’GetValueOrDefault()’的布尔值上

在这种情况下究竟发生了什么?我假设GetValueOrDefault()必须是所有布尔类型的方法?我在.NET文档中查看了这个并找到了这个定义:

The value of the Value property if the HasValue property is true;
otherwise,the default value of the current Nullable(Of T) object. The
type of the default value is the type argument of the current
Nullable(Of T) object,and the value of the default value consists
solely of binary zeroes.

我无法将此定义与.net mvc应用程序上的内容联系起来.

谢谢.

解决方法

GetValueOrDefault()不是bool的一部分,it’s part of Nullable<T>.这里的关键是在函数头中声明bool的语法:

public ActionResult Delete(int id,bool? saveChangesError)

问号是一个C#语言结构,它表明这不是一个bool,而是一个Nullable< bool>. bool为1的值类型不能为null.但有时如果他们可以的话会很有用.所以Nullable< T> struct存在是为了达到这个目的.

GetValueOrDefault()是该结构上的一个方法,如果没有指定值,它将返回bool的值或bool的默认值(which is false).

asp.net-mvc – ASP.NET mvc 4控制器参数始终为空时发送json到控制器,为什么?

asp.net-mvc – ASP.NET mvc 4控制器参数始终为空时发送json到控制器,为什么?

有一些类似的帖子已经在这里,并尝试每个解决方案建议,仍然不工作…我无法获得控制器内的价值,它总是为空.下面是代码.我错过了什么吗?

客户端javascript

function getChart() {
       JSONString3 = { HAxis : [{ Name : "monday" }] };
       jQuery.ajaxSettings.Traditional = true;
        $.ajax({
            url: "@Url.Action("getChart","SBM")",type: 'POST',contentType: 'json',dataType: 'html',data: JSONString3,success: function (data) {
                var imagestring = btoa(data);
                $('#Chartimage').attr('src',"data:image/png;base64," + imagestring + "?" + new       Date().getTime());
            }
        })
        jQuery.ajaxSettings.Traditional = false;
    }

MVC控制器

[Authorize]
    [HttpPost]
    public ActionResult getChart(YAxis HAxis)
    {
        YAxis XAxisvalue = HAxis;
        Charts chart = new Charts();
        MemoryStream ms = new MemoryStream();
        chart.Chart.SaveImage(ms);
        string image = Convert.ToBase64String(ms.GetBuffer());
        return File(ms.GetBuffer(),"image/png","Chart.png");
    }

模型

public class YAxis
{
    public string Name { get; set; }
}

解决方法

谢谢各位的指导和解决方案.该解决方案是您的所有建议的组合,所以我决定在一个帖子中进行整理.

解决问题的方法如下:

> contentType应该是application / json(如上面提到的Ant P)
> json数据应该是JSONString3 = {“Name”:“monday”}的形式(如上所述Ant P)
>发送给控制器之前,json应该被字符串化如下:JSONString3 = JSON.stringify(JSONString3)(如Quan建议)

客户端javascript

function getChart() {
               JSONString3 = { "Name" : "monday" };
               jQuery.ajaxSettings.Traditional = true;
                $.ajax({
                    url: "@Url.Action("getChart",contentType: 'application/json',data: JSON.stringify(JSONString3),success: function (data) {
                        var imagestring = btoa(data);
                        $('#Chartimage').attr('src'," + imagestring + "?" + new       Date().getTime());
                    }
                })
                jQuery.ajaxSettings.Traditional = false;
    }

MVC控制器

[Authorize]
[HttpPost]
public ActionResult getChart(YAxis HAxis)
{
    YAxis XAxisvalue = HAxis;
    Charts chart = new Charts();
    MemoryStream ms = new MemoryStream();
    chart.Chart.SaveImage(ms);
    string image = Convert.ToBase64String(ms.GetBuffer());
    return File(ms.GetBuffer(),"Chart.png");
}

模型

public class YAxis
{
    public string Name { get; set; }
}

而不是这样:

JSONString3 = { "Name" : "monday" };

我们做得到:

var JSONString3 = {};
JSONString.Name = "monday";

但是我们还需要在发布给控制器之前对对象进行字符串化

To pass multiple objects to controller,below is the example

客户端javascript

function getChart() {

        //first json object
        //note: each object Property name must be the same as it is in the Models classes on    server side
        Category = {};
        Category.Name = "Category1";
        Category.Values = [];
        Category.Values[0] = "CategoryValue1";
        Category.Values[1] = "CategoryValue2";

        //second json object
        XAxis = {};
        XAxis.Name = "XAxis1";
        XAxis.Values = [];
        XAxis.Values[0] = "XAxisValue1";
        XAxis.Values[1] = "XAxisValue2";

        //third json object
        YAxis = {};
        YAxis.Name = "YAxis1";

        //convert all three objects to string
        //note: each object name should be the same as the controller parameter is!!
        var StringToPost = JSON.stringify({CategoryObject : Category,XAxisObject : XAxis,YAxisObject : YAxis});

        $.ajax({
            url: "@Url.Action("getChart",contentType: "application/json",data: StringToPost,success: function (data) {
                var imagestring = btoa(data);
                $('#Chartimage').html(data);
            }
        })
    }

MVC控制器

[HttpPost]
public ActionResult getChart(Category CategoryObject,XAxis XAxisObject,YAxis YAxisObject)
{
    //do some stuff with objects here and return something to client
    return PartialView("_Chart");
}

类别模型

public class Category
{
    public string Name { get; set; }
    public List<string> Values { get; set; }
}

XAxis模型

public class XAxis
{
    public string Name { get; set; }
    public List<string> Values { get; set; }
}

YAX模型

public class YAxis
{
    public string Name { get; set; }
}

希望能帮助人澄清整个画面!

关于asp.net-mvc – asp.net mvc在控制器构建期间的任何时候都可以使用Session吗?的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于ASP.NET MVC在基控制器中处理Session、asp.net-core-mvc – 如何在Asp.Net Core MVC 1.0(又名MVC 6 RC1)中访问Session Timeout值?、asp.net-mvc – ASP.NET MVC 3 – 这个布尔值如何在控制器中运行?、asp.net-mvc – ASP.NET mvc 4控制器参数始终为空时发送json到控制器,为什么?等相关内容,可以在本站寻找。

本文标签: