1、Web.config配置上system.web节点下加入以下配置

<system.web>
<authentication mode="Forms">
<forms name=".wechat" loginUrl="url" timeout="30" protection="All" defaultUrl="/index.html" />
</authentication>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>

2、上代码

using Newtonsoft.Json;
using System;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Security; namespace KMHC.CTMS.DrugStore.Controllers
{
public class BaseApiController : ApiController
{
protected void SignIn(dynamic user)
{
if (user == null)
return;
var httpContext = HttpContext.Current; var version = 1;
var name = user.OpenId;
var now = DateTime.Now.ToLocalTime();
var expiration = now.Add(TimeSpan.FromDays(30));
var isPersistent = true;
var userData = JsonConvert.SerializeObject(user); var ticket = new FormsAuthenticationTicket(version, name, now, expiration, isPersistent, userData, FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath
};
cookie.Expires = ticket.Expiration;
if (FormsAuthentication.CookieDomain != null)
{
cookie.Domain = FormsAuthentication.CookieDomain;
} var url = HttpContext.Current.Request.Url.ToString();
if (!string.IsNullOrEmpty(url) && url.StartsWith("https"))
{
cookie.Secure = true;
} httpContext.Response.Cookies.Add(cookie); httpContext.User = new GenericPrincipal(new FormsIdentity(ticket), new string[] { "Wechat" });
} protected string OpenId
{
get
{
return this.User.Identity.Name;
}
} protected bool IsAuthenticated
{
get
{
return this.User.Identity.IsAuthenticated;
}
} protected dynamic UserInfo {
get {
var identity = (FormsIdentity)HttpContext.Current.User.Identity;
var user = JsonConvert.DeserializeObject<dynamic>(identity.Ticket.UserData);
return user;
}
}
}
}

3、默认地址获取

//index.html  <forms name=".wechat" loginUrl="url" timeout="30" protection="All" defaultUrl="/index.html" />
var defaultUrl= FormsAuthentication.DefaultUrl;

  

WebApi设置HttpContext.Current.User的更多相关文章

  1. 异步任务,HttpContext.Current为null解决办法

    最近在开发一个后台管理系统项目,为了提高登录的速度,就把记录登录日志放到一个异步任务里面. Action taskAction = () => { SaveLog(); }; Task task ...

  2. .net webapi 中使用session是出错 HttpContext.Current.Session==null

    最近在写.net webapi时发现 HttpContext.Current.Session==null  ,导致报错,后来查资料发现webapi中使用session时首先需要开启session功能, ...

  3. System.Web.HttpContext.Current.Server.MapPath("~/upload/SH") 未将对象引用设置为实例对象

    做项目的时候,System.Web.HttpContext.Current.Server.MapPath("~/upload/SH")   获取路径本来这个方法用的好好的 因为需要 ...

  4. 2014-08-26 解决HttpContext.Current.Session在ashx文件中出现“未将对象引用设置到对象的实例”的问题

    今天是在吾索实习的第35天. 最近在使用HttpContext.Current.Session来获取Session["..."]的值时,常常会弹出错误——“未将对象引用设置到对象的 ...

  5. HttpContext.Current.Server.MapPath("/") 未将对象设置到对象的实例异常。

    多线程中的System.Web.HttpContext.Current.Server.MapPath("/") 多线程中Server.MapPath会失效... 网上找到几种解决方 ...

  6. HttpContext.Current.Session[strName]未将对象引用设置到对象的实例

    项目开发是在4.5.1上,不知道为啥客户提供的服务器上安装的是4.5,差别不大也没去升级,然后部署MVC的时候web.config报错 <system.web> <compilati ...

  7. HttpContext.Current.Server.MapPath("") 未将对象设置到引用的

    在多线程中使用该方法获取目录报错:未将对象设置到引用 #region 上传图片到腾讯 public async Task<Result> UploadImageToWX(string ba ...

  8. 异步 HttpContext.Current 为空null 另一种解决方法

    1.场景 在导入通讯录过程中,把导入的失败.成功的号码数进行统计,然后保存到session中,客户端通过轮询显示状态. 在实现过程中,使用的async调用方法,出现HttpContext.Curren ...

  9. WebApi设置SessionState为Required

    public override void Init() { //在注册管道事件中 require session state //只能在引发“HttpApplication.AcquireReques ...

随机推荐

  1. ios12更新开发者需要做的

    1.StatusBar内部结构改变 现象:crash crash log: -[_UIStatusBarIdentifier isEqualToString:]: unrecognized selec ...

  2. iBATIS typeHandler selectKey

    typeHandler 是针对把数据库里面的某列的数据类型转换的应用程序中的数据类型,简单的说就是把 type=>dbType  反之把dbType=>type. 例如数据库某列的内容是l ...

  3. vue中的$route和$router的区别

    1. $route是一个对象 可以获取当前页面的路由的路径query.params.meta等参数: 2.$router是VueRouter的一个实例对象 在options中可以获取路由的routes ...

  4. python 类的定义 实例化 实例完后初始化

    先来看看 类的__init__, 类的__new__ , 元类的__new__的执行顺序 class TMetaclass(type): def __new__(cls,name,bases,attr ...

  5. 【leetcode】476. Number Complement

    problem 476. Number Complement solution1: class Solution { public: int findComplement(int num) { //正 ...

  6. Linux 添加DNS配置

    Centos7.5 系统,保存退出后自动生效 vi /etc/resolv.conf #阿里云DNS nameserver 223.5.5.5nameserver 223.6.6.6 #百度DNSna ...

  7. 1(2)IO流---字节流

    一.分类 字节流(不适用于文本) InputStream OutputStream 字符流 Reader Writer  二.字节流 1.概述     InputStream 字节输入流,是被读的,抽 ...

  8. 陈斌python语言基础与应用00

    软件改变生活:购物.餐饮.商旅出行.资料查找... Everybody in this country should learn how to program a computer...because ...

  9. visual stutio 20017

    Visual Studio 2017入門: https://www.atmarkit.co.jp/ait/articles/1704/10/news026.html vb 手册: http://vb. ...

  10. 哈希表(Hash Map)

    今天第一次做Leetcode用到了散列表,之前学的数据结构的内容都忘了,正好趁热打铁补一补. 摘自其他博客的一个整合. 一.哈希表简介 数据结构的物理存储结构只有两种:顺序存储结构和链式存储结构(像栈 ...