由于项目实际需要,我希望让WebApi服务也能支持Session,所以便查找资料按照网上的方法开始着手实验。

然后就有了以下的代码,主要是说让WebApi支持Session,要重写Global.asax的Init方法

public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.EnableCors();
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); } public override void Init()//重写这个方法
{
PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
} private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
} }

  重写方法后,准备动手编写测试的Controller代码 如下,很简单的几句代码,A方法模拟第一次请求将携带的参数存入Session,其中键和值都为传入的参数appid,B方法是返回键为appid的session的值。

 public class GetDataController : ApiController
{ [HttpGet]
public void A(string appid)
{ System.Web.HttpContext.Current.Session[appid] = appid;
System.Web.HttpContext.Current.Session.Timeout =1;
}
[HttpGet]
public ResponseData B(string appid)
{ return new ResponseData() { data = System.Web.HttpContext.Current.Session[appid].ToString(), isSuccess = true };
}
}

  用谷歌浏览器,模拟A\B两个请求,实验成功!!!!!很是高兴!!

但问题来了,通过浏览器运行可以取到session的值,但是在手机的移动设备端,访问居然每次获取session的值都是null,有些不解,便开始寻找问题的根源所在,为什么浏览器正常,然而在移动设备模拟就不行了呢??????     功夫不负有心人,终于找到了问题所在,大概原因就是说,session是靠一个的cookie来区分的,客户端每次访问要携带这个cookie才能保持session的状态。于是我便用控制台模拟移动端进行测试。代码如下:

class Program
{
static void Main(string[] args)
{ GetMethod("http://192.168.1.9:8828/api/GetDAta/A?appid=abc"); // PostMethod("http://localhost:8828/api/GetDAta/Login/");
Console.ReadKey();
GetMethodTest("http://192.168.1.9:8828/api/GetDAta/b?appid=abc");
Console.ReadKey();
}
private static CookieContainer m_Cookie = new CookieContainer();
private static void GetMethod(String url)
{ HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = m_Cookie;
string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(url));
m_Cookie.SetCookies(new Uri(url), cookieheader);
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{ StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
} }
private static void GetMethodTest(String url)
{ HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = m_Cookie;
m_Cookie = request.CookieContainer;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{ StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
} }
}
GetMethod为模拟访问A服务,其中以下代码,就是在访问A的时候设置cookie
            request.CookieContainer = m_Cookie;
string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(url));
m_Cookie.SetCookies(new Uri(url), cookieheader);
GetMethodTest为模拟访问B服务,请求时候需要携带上次访问A的cookie的信息,代码如下
            request.CookieContainer = m_Cookie;
m_Cookie = request.CookieContainer;

到此,一切测试完毕,正常运行。

初学webapi,哪有不对,希望园友多多指教!!!!!!!

 
 

 

最新文章

  1. webpack 往右一点之 “你好,初次见面”
  2. 【代码笔记】iOS-侧滑效果
  3. Scala implicit
  4. Reading With Purpose: A grand experiment
  5. pdf嵌入字体
  6. R语言putty中直接使用X11(Xming)绘图
  7. for循环里面的判断条件
  8. MySql密码丢失
  9. iOS7 StatusBar 使用小结
  10. MySQL:Error : Tablespace for table '`database`.`temp`' exists. Please DISCARD the tablespace before IMPORT.解决办法
  11. storage size of 'xxx' isn't known问题出现的可能原因之一
  12. [读书笔记] 一、Spring boot项目搭建与配置文件
  13. java处理含有中文的字符串.
  14. CSS字体样式属性
  15. 检索 COM 类工厂中 CLSID 为 {91493441-5A91-11CF-8700-00AA0060263B} 的组件失败
  16. Confluence 6 数据库表-内容(Content)
  17. flask通过form表单一次上传多个文件
  18. delphi 右键删除dbgrid行
  19. thinkphp得到客户端的ip
  20. apt小问题

热门文章

  1. 对C标准中空白字符(空格、回车符(\r)、换行符(\n)、水平制表符(\t)、垂直制表符(\v)、换页符(\f))的理解
  2. C/C++捕获段错误,打印出错的具体位置(精确到哪一行)
  3. zoj3802:easy 2048 again(状压dp)
  4. 上传图片代码(chuantouxiang.php+touxiangchuli.php)
  5. js如何判断字符串是否进行过window.btoa()转码
  6. 第34讲 UI组件之 ProgressDialog和Message
  7. Redhat6.4 配置本地网络的FTP YUM源
  8. 用递归翻转一个栈 Reverse a stack using recursion
  9. Oracle—RMAN备份(一)
  10. web请求的处理流程