##Token验证WeixinCon
using Sy;
namespace WeC
{
public class WeixinController : Controller
{
public string Index()
{
var token = "chinalex";
//与微信公众账号后台的Token设置保持一致,区分大小写
if (token))
{
return ;
}
var echoString = reque["echoStr"];
//string signature = this.Reque["signature"];
//string timestamp = this.Reque["timestamp"];
//string nonce = this.Reque["nonce"];
return echoString;
}
}
}
##HomeCon
using Sy;
using Sy;
using Sy;
using Sy;
using New;
using Wec;
using WeC;
namespace WeC
{
public class HomeController : Controller
{
public static int sum;
public static string openid;
//用户的唯一标识
public static string nickname;
//用户昵称
public static string sex;
//用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
public static string province;
//用户个人资料填写的省份
public static string city;
//普通用户个人资料填写的城市
public static string country;
//国家,如中国为CN
public static string headimgurl;
//用户头像
public static string privilege;
//用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
public static string unionid;
//只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
private static userInfo usInfo;
//
// GET: /Home/
//第一步:用户同意授权,获取code
public ActionResult Index()
{
var flag = 0;
var code = Reque["code"];
var state = Reque["state"];
if (code != "" && state != null && flag == 0)
{
flag = 1;
at(code);
//拿code获取token跟openid
ViewBag.Message_ViewBag = u;
}
return View();
}
//第二步:通过code换取网页授权access_token
public void at(string code)
{
var AppID = "wxxxxxxx";
var AppSecret = "fffffffffffffffffffff";
var strUrl =
"{0}&secret={1}&code={2}&grant_type=authorization_code";
strUrl = (strUrl, AppID, AppSecret, code);
var request = (HttpWebReque(strUrl);
var response = (HttpWebResponse();
var responseString = new StreamReader()).ReadToEnd();
var at = J;atoken>(responseString);
rt(AppID, at.refresh_token);
}
//第三步:刷新refresh_token(如果需要)
public void rt(string AppID, string refresh_token)
{
var strUrl ="{0}&grant_type=refresh_token&refresh_token={1}";
strUrl = (strUrl, AppID, refresh_token);
var request = (HttpWebReque(strUrl);
var response = (HttpWebResponse();
var responseString = new StreamReader()).ReadToEnd();
var rt = J;rtoken>(responseString);
gUserInfo, rt.openid);
}
//第四步:拉取用户信息(需scope为 snsapi_userinfo)
[HttpGet]
public void gUserInfo(string access_token, string openId)
{
sum = sum + 1;
if (access_token != null)
{
var strUrl = "{0}&openid={1}&lang=zh_CN";
strUrl = (strUrl, access_token, openId);
var jsonStr = H(strUrl);
usInfo = new userInfo();
u = Tools.GetJsonValue(jsonStr, "openid");
u = Tools.GetJsonValue(jsonStr, "nickname");
u = Tools.GetJsonValue(jsonStr, "sex");
u = Tools.GetJsonValue(jsonStr, "province");
u = Tools.GetJsonValue(jsonStr, "city");
u = Tools.GetJsonValue(jsonStr, "country");
u = Tools.GetJsonValue(jsonStr, "headimgurl");
u = Tools.GetJsonValue(jsonStr, "privilege");
u = Tools.GetJsonValue(jsonStr, "unionid");
}
else
{
Debug.Write("没有拿到access_token:" + sum);
//return View();
}
}
private class atoken
{
public string access_token { set; get; }
public string expires_in { set; get; }
public string refresh_token { set; get; }
public string openid { set; get; }
public string scope { set; get; }
}
private class rtoken
{
public string access_token { set; get; }
public string expires_in { set; get; }
public string refresh_token { set; get; }
public string openid { set; get; }
public string scope { set; get; }
}
private class userInfo
{
public string openid { set; get; }
public string nickname { set; get; }
public string sex { set; get; }
public string province { set; get; }
public string city { set; get; }
public string country { set; get; }
public string headimgurl { set; get; }
public string privilege { set; get; }
public string unionid { set; get; }
}
}
}
##H
using System;
using Sy;
using Sy;
using Sy;
namespace Wec
{
public class HttpCrossDomain
{
/// <summary>
/// 跨域访问
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Post(string url, string param, int time = 60000)
{
var address = new Uri(url);
var request = WebReque(address) as HttpWebRequest;
reque = "POST";
reque = "application/json;charset=utf-8";
//"application/x-www-form-urlencoded";
reque = time;
var byteData = Encoding.UTF8.GetBytes(param == null ? "" : param);
reque = by;
using (var postStream = reque())
{
(byteData, 0, by);
}
var result = "";
using (var response = reque() as HttpWebResponse)
{
var reader = new StreamReader());
result = reader.ReadToEnd();
}
return result;
}
/// <summary>
/// 跨域访问
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Get(string url, int time = 60000)
{
var address = new Uri(url);
var request = WebReque(address) as HttpWebRequest;
reque = "GET";
reque = "application/json;charset=utf-8";
//"application/x-www-form-urlencoded";
reque = time;
var result = "";
try
{
using (var response = reque() as HttpWebResponse)
{
var reader = new StreamReader());
result = reader.ReadToEnd();
}
}
catch
{
result = "";
}
return result;
}
}
}
##Tools.cs
using System;
using Sy;
using Sy.Drawing2D;
using Sy.Imaging;
using Sy;
using Sy;
using Sy;
using Encoder = Sy.Imaging.Encoder;
namespace WeC
{
public class Tools
{
private static readonly string[] strs =
{
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"
};
/// <summary>
/// Sha1
/// </summary>
/// <param name="orgStr"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Sha1(string orgStr, string encode ="UTF-8")
{
var sha1 = new SHA1Managed();
var sha1bytes = Encoding.GetEncoding(encode).GetBytes(orgStr);
var resultHash = (sha1bytes);
var sha1String = Bi(resultHash).ToLower();
sha1String = ("-", "");
return sha1String;
}
#region 获取Json字符串某节点的值
/// <summary>
/// 获取Json字符串某节点的值
/// </summary>
public static string GetJsonValue(string jsonStr, string key)
{
var result = ;
if (!(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
var index = j(key) + key.Length + 1;
if (index > key.Length + 1)
{
//先截<span id="3_nwp" style="width: auto; height: auto; float: none;"><a id="3_nwl" href=";cf=5&ch=0&di=128&fv=17&jk=17f5c9861aa0f402&k=%B6%BA%BA%C5&k0=%B6%BA%BA%C5&kdi0=0&luki=2&n=10&p=baidu&q=00007110_cpr&rb=0&rs=1&seller_id=1&sid=2f4a01a86c9f517&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1704338&u=http%3A%2F%2Fwww%2Edaxueit%2Ecom%2Farticle%2F5631%2Ehtml&urlid=0" target="_blank" mpid="3" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">逗号</span></a></span>,若是最后一个,截“}”号,取最小值
var end = j(',', index);
if (end == -1)
{
end = j('}', index);
}
result = j(index, end - index);
result = re('"', ' ', '\'');
//过滤引号或空格
}
}
return result;
}
#endregion
/// <summary>
/// 创建时间戳
/// </summary>
/// <returns></returns>
public static long CreatenTimestamp()
{
return ().Ticks - 6200000)/10000000;
}
/// <summary>
/// 创建随机字符串
/// 本代码来自开源微信SDK项目:
/// </summary>
/// <returns></returns>
public static string CreatenNonce_str()
{
var r = new Random();
var sb = new StringBuilder();
var length = ;
for (var i = 0; i < 15; i++)
{
(strs[r.Next(length - 1)]);
}
return ();
}
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片</param>
/// <param name="dFile">压缩后保存位置</param>
/// <param name="dHeight">高度</param>
/// <param name="dWidth"></param>
/// <param name="flag">压缩质量 1-100</param>
/// <returns></returns>
public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
{
var iSource = Image.FromFile(sFile);
var tFormat = iSource.RawFormat;
int sW = 0, sH = 0;
//按比例缩放
var tem_size = new Size, iSource.Height);
if > dHeight || > dWidth)
//将改成c#中的或者操作符号
{
if dHeight > )
{
sW = dWidth;
sH = dWidth/;
}
else
{
sH = dHeight;
sW = dHeight/;
}
}
else
{
sW = ;
sH = ;
}
var ob = new Bitmap(dWidth, dHeight);
var g = Gra(ob);
g.Clear);
g.CompositingQuality = Com;
g.SmoothingMode = Smoo;
g.InterpolationMode = In;
g.DrawImage(iSource, new Rectangle((dWidth - sW)/2, (dHeight - sH)/2, sW, sH), 0, 0, iSource.Width,
iSource.Height, Gra);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
var ep = new EncoderParameters();
var qy = new long[1];
qy[0] = flag;
//设置压缩的比例1-100
var eParam = new EncoderParameter, qy);
ep.Param[0] = eParam;
try
{
var arrayICI = ImageCodecIn();
ImageCodecInfo jpegICIinfo = null;
for (var x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].Forma("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);
//dFile是压缩后的新路径
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
/// <summary>
/// 压缩图片
/// </summary>
/// <returns></returns>
public static bool CompressImages(string pathOriginal, string pathDestination)
{
var files = Direc(pathOriginal);
var bos = false;
foreach (var file in files)
{
var strImgPathOriginal = pathOriginal + Pa(file).Trim();
if (strImgPathOriginal))
{
//原始图片存在
var strImgPath = pathDestination + Pa(file).Trim();
if (!File.Exists(strImgPath))
{
//压缩图片不存在
//压缩图片
bos = GetPicThumbnail(strImgPathOriginal, strImgPath, 200, 200, 100);
if (!bos)
{
break;
}
}
}
}
return true;
}
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片Img</param>
/// <param name="dFile">压缩后保存位置</param>
/// <param name="dHeight">高度</param>
/// <param name="dWidth"></param>
/// <param name="flag">压缩质量 1-100</param>
/// <returns></returns>
public static bool GetPicThumbnails(Image iSource, string dFile, int dHeight, int dWidth, int flag)
{
//Sy.Image iSource = Sy.Image.FromFile(sFile);
var tFormat = iSource.RawFormat;
int sW = 0, sH = 0;
var temp = 0;
//按比例缩放
if > iSource.Height)
{
temp = iSource.Height;
}
else
{
temp = iSource.Width;
}
var tem_size = new Size(temp, temp);
if > dHeight || > dWidth)
//将改成c#中的或者操作符号
{
if dHeight > )
{
sW = dWidth;
sH = dWidth/;
}
else
{
sH = dHeight;
sW = dHeight/;
}
}
else
{
sW = ;
sH = ;
}
var ob = new Bitmap(dWidth, dHeight);
var g = Gra(ob);
g.Clear);
g.CompositingQuality = Com;
g.SmoothingMode = Smoo;
g.InterpolationMode = In;
g.DrawImage(iSource, new Rectangle((dWidth - sW)/2, (dHeight - sH)/2, sW, sH), 0, 0, iSource.Width,
iSource.Height, Gra);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
var ep = new EncoderParameters();
var qy = new long[1];
qy[0] = flag;
//设置压缩的比例1-100
var eParam = new EncoderParameter, qy);
ep.Param[0] = eParam;
try
{
var arrayICI = ImageCodecIn();
ImageCodecInfo jpegICIinfo = null;
for (var x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].Forma("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);
//dFile是压缩后的新路径
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
/// <summary>
/// 按照指定大小缩放图片,但是为了保证图片宽高比将对图片从中心进行截取,达到图片不被拉伸的效果
/// </summary>
/// <param name="srcImage"></param>
/// <param name="iWidth"></param>
/// <param name="iHeight"></param>
/// <returns></returns>
public static Bitmap SizeImageWithOldPercent(Image srcImage, int iWidth, int iHeight)
{
try
{
// 要截取图片的宽度(临时图片)
var newW = ;
// 要截取图片的高度(临时图片)
var newH = ;
// 截取开始横坐标(临时图片)
var newX = 0;
// 截取开始纵坐标(临时图片)
var newY = 0;
// 截取比例(临时图片)
double whPercent = 1;
whPercent = iWidth/(double) iHeight(/(double) );
if (whPercent > 1)
{
// 当前图片宽度对于要截取比例过大时
newW = int.Parse(/whPercent).ToString());
}
else if (whPercent < 1)
{
// 当前图片高度对于要截取比例过大时
newH = int.Parse(whPercent).ToString());
}
if (newW != )
{
// 宽度有变化时,调整开始截取的横坐标
newX = Ma(((double) - newW)/2).ToString()));
}
else if (newH == )
{
// 高度有变化时,调整开始截取的纵坐标
newY = Ma(( - (double) newH)/2).ToString()));
}
// 取得符合比例的临时文件
var cutedImage = CutImage(srcImage, newX, newY, newW, newH);
// 保存到的文件
var b = new Bitmap(iWidth, iHeight);
var g = Gra(b);
// 插值算法的质量
g.InterpolationMode = In;
g.DrawImage(cutedImage, new Rectangle(0, 0, iWidth,iHeight),
new Rectangle(0, 0, cu, cu), Gra);
g.Dispose();
//return b;
return cutedImage;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 剪裁 -- 用GDI+
/// </summary>
/// <param name="b">原始Bitmap</param>
/// <param name="StartX">开始坐标X</param>
/// <param name="StartY">开始坐标Y</param>
/// <param name="iWidth">宽度</param>
/// <param name="iHeight">高度</param>
/// <returns>剪裁后的Bitmap</returns>
public static Bitmap CutImage(Image b, int StartX, int StartY, int iWidth, int iHeight)
{
if (b == null)
{
return null;
}
var w = b.Width;
var h = b.Height;
if (StartX >= w || StartY >= h)
{
// 开始截取坐标过大时,结束处理
return null;
}
if (StartX + iWidth > w)
{
// 宽度过大时只截取到最大大小
iWidth = w - StartX;
}
if (StartY + iHeight > h)
{
// 高度过大时只截取到最大大小
iHeight = h - StartY;
}
try
{
var bmpOut = new Bitmap(iWidth, iHeight);
var g = Gra(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight),
Gra);
g.Dispose();
return bmpOut;
}
catch
{
return null;
}
}
/// <summary>
/// 切原始图片
/// </summary>
/// <param name="b"></param>
/// <param name="StartX"></param>
/// <param name="StartY"></param>
/// <param name="iWidth"></param>
/// <param name="iHeight"></param>
/// <returns></returns>
public static Bitmap CutImageOriginal(Image b)
{
var imageSource = b;
var orgWidth = imageSource.Width;
var orgHight = imageSource.Height;
var width = 0;
var height = 0;
if (orgWidth > orgHight)
{
width = orgHight;
height = orgHight;
}
else
{
width = orgWidth;
height = orgWidth;
}
var cropArea = new Rectangle();
var x = orgWidth/2 - width/2;
//(145是从中间开始向两边截图的宽度,可以自定义)
var y = orgHight/2 - height/2;
cro = x;
cro = y;
cro = width;
cro = height;
var bmpImage = new Bitmap(imageSource);
var bmpCrop = bm(cropArea, bm);
return bmpCrop;
}
/// <summary>
/// 生成两个数之间的随机数
/// </summary>
/// <param name="min">最小值</param>
/// <param name="max">最大值</param>
/// <returns></returns>
public static int GetRandNum(int min, int max)
{
var r = new Random().GetHashCode());
return r.Next(min, max);
}
/// <summary>返回两个经纬度坐标点的距离(单位:米) by Alex.Y</summary>
/// <param name="Longtiude">来源坐标经度Y</param>
/// <param name="Latitude">来源坐标经度X</param>
/// <param name="Longtiude2">目标坐标经度Y</param>
/// <param name="Latitude2">目标坐标经度X</param>
/// <returns>返回距离(米)</returns>
public static double getMapDistance(double Longtiude, double Latitude, double Longtiude2, double Latitude2)
{
var lat1 = Latitude;
var lon1 = Longtiude;
var lat2 = Latitude2;
var lon2 = Longtiude2;
var earthRadius = 6371;
//appxoximate radius in miles 6378.137
var factor = Ma;
var dLat = (lat2 - lat1)factor;
var dLon = (lon2 - lon1)factor;
var a = Ma(dLat/2)Ma(dLat/2) + Ma(lat1factor)
Ma(lat2factor)Ma(dLon/2)Ma(dLon/2);
var c = 2Ma(a), Ma(1 - a));
var d = earthRadiusc1000;
return d;
}
}
}
@{
ViewBag.Title = "Index";
}
<div style="border: 1px solid red; height: 600px; margin: 0 auto; width: 50%;">
<div style="text-align: center;">
<h2 style="margin-top: 20px;">
微信授权登录
</h2>
![](~/Image)
</div>
<br />
昵称:@H)
</div>