1. 程式人生 > >微信授權封裝,歡迎使用

微信授權封裝,歡迎使用

extension vat oauth gen oid bsp .cn pre catch

FastDev.WeiXinHelper

引用示例:

基於Mvc網站繼續說明:

1.自定義屬性 UserAuthorizeAttribute

using FastDev.Log;
using FastDev.Mvc.Extension;
using FastDev.WeiXinHelper.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TestWeiXinWap.Controllers.Filter
{

/// <summary>
///
/// </summary>
/// <seealso cref="AuthorizeAttribute" />
public class UserAuthorizeAttribute : AuthorizeAttribute
{
private static string appId = "-------------------------";
private static string appSecret = "-------------------------";
private static string authdomain = "http://---------------------------/";
/// <summary>
/// 登錄篩選器實現
/// </summary>
/// <param name="filterContext">filterContext</param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
try
{
if (!OAuth2.IsAuth)
{
OAuth2.FilterContext = filterContext;
OAuth2.AppId = appId;
OAuth2.AppSecret = appSecret;
var refreUrl = filterContext.RequestContext.HttpContext.Request.Url.ToString();
var uri = new Uri(refreUrl);
refreUrl = refreUrl.Replace(":" + uri.Port, "");
var guid = Guid.NewGuid().ToString();
var authUrl = OAuth2.GetAuthorizeUrl(authdomain, refreUrl, 1, guid);

filterContext.Result = new RedirectTopResult(authUrl);
}
}
catch (Exception ex)
{
LogHelper.WriteLog(ex, "微信授權限出錯,重新授權...");
}
}
}
}

2.在控制上添加屬性

using FastDev.WeiXinHelper.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TestWeiXinWap.Controllers
{

[UserAuthorize]

public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
var wxUserInfo = OAuth2.WxUserInfo;

return View(wxUserInfo);
}

public ActionResult Remove()
{
OAuth2.WxUserInfo = null;

return View("Index");
}
}
}

以上代碼替換自己的AppID 和AppSecret 和授權域名,從哪個頁面訪問,授權完成會回調到 當前頁面。

點擊下載 所屬dll

微信授權封裝,歡迎使用