webapi中使用session

修改global.cs里面的内容
using System;
using System.Web;
using System.Web.Routing;
using System.Web.Http;
using System.Web.Http.WebHost;
using System.Web.SessionState; namespace ApiControllerExample
{
public class Global : System.Web.HttpApplication
{ public override void Init()
{
//取下注释下面这行语句,将使得全部Api都可以访问Session
//this.PostAuthenticateRequest += (s, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
base.Init();
} protected void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes); // 注册路由
}
} public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState
{
public SessionableControllerHandler(RouteData routeData) : base(routeData) { }
} public class SessionStateRouteHandler : IRouteHandler
{
IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
{
return new SessionableControllerHandler(requestContext.RouteData);
}
} public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "WebApiRoute1",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
).RouteHandler = new SessionStateRouteHandler(); // 使用Session routes.MapHttpRoute(
name: "WebApiRoute2",
routeTemplate: "api/{controller}/{id}/{id2}",
defaults: new{id = RouteParameter.Optional }
); // 不使用Session
}
}
} webapi用例:
using System;
using System.Web.Http; namespace ApiControllerExample
{
public class StateController : ApiController
{
public string Get(int id)
{
try
{
return GetStateInfo(id);
}
catch (Exception err)
{
return "excep: " + err.Message;
}
} private string GetStateInfo(int id)
{
System.Web.HttpContext context = System.Web.HttpContext.Current; if (id == 1)
{
return context.Session["state"].ToString();
}
else if (id == 2)
{
return context.Cache["state"].ToString();
}
else
{
return context.Application["state"].ToString();
}
} //这个方法无法使用Session
public string Get(int id, int id2)
{
System.Web.HttpContext context = System.Web.HttpContext.Current; try
{
return context.Session["state"].ToString();
}
catch (Exception err)
{
return "excep: " + err.Message;
}
}
}
}

  

Web APi全局启动Session(一)

以下皆在Global.asax全局文件中进行。

第一步(定义两个变量)

 private const string WebApiPrefix = "APi";
private static string WebApiExecutePath = string.Format("~/{0}", WebApiPrefix);

第二步(获取当前请求的路径)

 private bool isWebAPiRequest()
{
  return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiExecutePath);
}

第三步(若请求Web APi则启动Session)

        protected void Application_PostAuthorizeRequest()
{
if (isWebAPiRequest())
{
HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
}

第四步(测试代码)

        protected void Session_Start()
{
HttpContext.Current.Session.Add("xpy0928", "嗨-博客");
var session_value = HttpContext.Current.Session["xpy0928"];
}

Web APi全局启动Session(二)

之前我们在Web APi系列中讲到过HttpControllerRouteHandler,此类中的GetHttpHandler方法返回HttpControllerHandler的一个实例即HttpHandler,通过此HttpHandler是进入Web APi消息处理管道的入口点,我们可以使用在IHttpHandler上的Session实现IRquiressionstate接口即可。

第一步(启动Session)

        protected void Application_PostAuthorizeRequest()
{
HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

第二步(自定义实现HttpHandler)

    public class EnableSession_ControllerHandler : HttpControllerHandler, IRequiresSessionState
{
public EnableSession_ControllerHandler(RouteData routeData)
: base(routeData)
{ }
}

第三步(获取HttpHandler)

    public class EnableSession_ControllerHandler : HttpControllerHandler, IRequiresSessionState
{
public EnableSession_ControllerHandler(RouteData routeData)
: base(routeData)
{ }
}

第四步(路由配置进行获取自定义RouteHandler)

          routes.MapHttpRoute(
name: "DefaultAPi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = UrlParameter.Optional }
).RouteHandler = new EnableSession_HttpControllerRouteHandler();

第五步(在Web APi配置文件中实现自定义HttpControllerRouteHandler)

        public static void Register(HttpConfiguration config)
{
var httpControllerRouteHandler = typeof(HttpControllerRouteHandler).GetField("_instance",
BindingFlags.Static |
BindingFlags.NonPublic); if (httpControllerRouteHandler != null)
{
httpControllerRouteHandler.SetValue(null,
new Lazy<HttpControllerRouteHandler>(() => new EnableSession_HttpControllerRouteHandler(), true));
} config.MapHttpAttributeRoutes(); }

此时运行将出现如下错误:

第六步(测试代码)

        public void Get()
{
object context;
if (Request.Properties.TryGetValue("MS_HttpContext", out context))
{
var httpContext = context as HttpContextBase;
if (httpContext != null && httpContext.Session != null)
{
var lastValue = httpContext.Session["xpy0928"] as int?;
httpContext.Session["xpy0928"] = "博客园";
var session_value = httpContext.Session["xpy0928"];
}
}
}

总结

以上两种方法皆可在Web APi中启动Session,你觉得那个简单就按照对应的来。我们需要注意一个问题是:在Web APi中,Web APi是不依赖于HttpContext,也就是HttpContext.Current肯定是为null的,我们要访问Session或者其他对象需要使用Rquest对象中的属性Properties来获得你想的值或者来设置值。

在Controller里:
 public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            var context = HttpContext.Current;
            context.Session["a"] = "aaa";
            return new string[] { "value1", "value2" };
           
        }
 
        // GET api/values/5
        public string Get(int id)
        {
            var ses = HttpContext.Current.Session["a"];
            return ses.ToString();
        }
    }
 
执行时出报异常,这时要在Global.asax里添加:开启Session功能
 public class WebApiApplication : System.Web.HttpApplication
    {
        public override void Init()
        {
            this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            base.Init();
        }
----------------------------------------------------------------------------------------------
 
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“sv”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class sv : Isv
 
  <system.serviceModel>
    <services>
      <service name="Tools.sv">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration=""
          contract="Tools.Isv" />
      </service>
    </services>
    <bindings />
    <behaviors>
      <endpointBehaviors>
        <behavior name="">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <standardEndpoints />
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"></serviceHostingEnvironment>
 
												

webapi session的更多相关文章

  1. asp.net core webapi Session 跨域

    在ajax 请求是也要加相应的东西 $.ajax({ url:url, //加上这句话 xhrFields: { withCredentials: true } success:function(re ...

  2. asp.net core webapi Session 内存缓存

    Startup.cs文件中的ConfigureServices方法配置: #region Session内存缓存 services.Configure<CookiePolicyOptions&g ...

  3. WebApi Session支持

    代码: WebApiConfig using System; using System.Collections.Generic; using System.Linq; using System.Net ...

  4. WebAPI中无法获取Session对象的解决办法

    在MVC的WebApi中默认是没有开启Session会话支持的.需要在Global中重写Init方法来指定会话需要支持的类型 public override void Init() { PostAut ...

  5. 在WebAPI使用Session

    最近在改写WebApp时要将以前用泛型处理例程写的Captcha 改成使用WebApi 来实作机制,在实作的过程中发现使用IRequiresSessionState session也无法使用(cont ...

  6. webapi mvc session一直获取不到问题

    前一段时间在给移动端写接口时遇到一个调用接口发送邮箱 session 一直获取不到的问题.我来给遇到问题的同志们说一说 自个在网上查了好多资料,问了一些朋友后.终于找到解决方案了. 大家都知道weba ...

  7. 启用 mvc webapi 的 session功能可用

    默认 mvc webapi 不开启 session 会话支持 所以需要修改配置,在 Global 开启 session 支持 如下: 1.重写 init() 方法 public override vo ...

  8. MVC4+WebApi+Redis Session共享练习(下)

    上一篇文章我们主要讲解了一些webApi和redis缓存操作,这篇文章我们主要说一些MVC相关的知识(过滤器和错误处理),及采用ajax调用webApi服务. 本篇例子采用的开发环境为:VS2010( ...

  9. MVC4+WebApi+Redis Session共享练习(上)

    这几天生病了,也没有心情写博客,北京医院真心伤不起呀,钱不少花,病没治好,还增加了新病,哎不说了,周末还得去大医院检查一下,趁女盆友还没有回来,把前几天写的东西总结一下.本文也会接触一点webApi的 ...

随机推荐

  1. 第10组 Alpha冲刺(6/6)

    链接部分 队名:女生都队 组长博客: 博客链接 作业博客:博客链接 小组内容 恩泽(组长) 过去两天完成了哪些任务 描述 tomcat的学习与实现 服务器后端部署,API接口的beta版实现 后端代码 ...

  2. ZooKeeper和ZAB协议

    前言 ZooKeeper是一个提供高可用,一致性,高性能的保证读写顺序的存储系统.ZAB协议为ZooKeeper专门设计的一种支持数据一致性的原子广播协议. 演示环境 $ uname -a Darwi ...

  3. RPC接口测试(一)什么是 RPC 框架

    什么是 RPC 框架 RPC 框架----- 远程过程调用协议RPC(Remote Procedure Call Protocol)-----允许像调用本地服务一样调用远程服务. RPC是指远程过程调 ...

  4. MXNet 定义新激活函数(Custom new activation function)

    https://blog.csdn.net/weixin_34260991/article/details/87106463 这里使用比较简单的定义方式,只是在原有的激活函数调用中加入. 准备工作下载 ...

  5. C# Newtonsoft.Json解析json字符串处理 - JToken 用法

    //*调用服务器API(获取可以处理的文件) //1.使用JSON通信协议(调用[待化验任务API]) String retData = null; { JToken json = JToken.Pa ...

  6. WebGL学习笔记(四):绘图

    图元 WebGL可以绘制非常复杂的3D模型,这些模型都是由下面3种基本几何图元构成的,下面我们来详细的看看. 三角形 WebGL中任何复杂的模型,都是由三角形组合而成的,可以说三角形是任意形状的最小构 ...

  7. [译]使用to_dict将pandas.DataFrame转换为Python中的字典列表

    pandas.DataFrame.to_json返回的是JSON字符串,不是字典. 可以使用to_dict进行字典转换. 使用orient指定方向. >>> df col1 col2 ...

  8. [LeetCode] 82. Remove Duplicates from Sorted List II 移除有序链表中的重复项 II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...

  9. [LeetCode] 257. Binary Tree Paths 二叉树路径

    Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 ...

  10. [LeetCode] 346. Moving Average from Data Stream 从数据流中移动平均值

    Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...