AuthController.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Senparc.Weixin.MP.AdvancedAPIs;
  7. using Senparc.Weixin;
  8. using Microsoft.AspNetCore.Http;
  9. using Senparc.Weixin.Entities;
  10. using Microsoft.Extensions.Options;
  11. // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
  12. namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
  13. {
  14. [Route("api/[controller]")]
  15. public class AuthController : BaseController
  16. {
  17. public AuthController(IOptions<SenparcWeixinSetting> senparcWeixinSetting) : base(senparcWeixinSetting)
  18. {
  19. }
  20. [HttpGet]
  21. public ActionResult Get(string code, string state, string returnUrl)
  22. {
  23. if (string.IsNullOrEmpty(code))
  24. {
  25. return Content("您拒绝了授权!");
  26. }
  27. if (!state.Contains("|"))
  28. {
  29. //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
  30. //实际上可以存任何想传递的数据,比如用户ID
  31. return Content("验证失败!请从正规途径进入!1001");
  32. }
  33. try
  34. {
  35. //通过,用code换取access_token
  36. var openIdResult = OAuthApi.GetAccessToken(appId, appSecret, code);
  37. if (openIdResult.errcode != ReturnCode.请求成功)
  38. {
  39. return Content("错误:" + openIdResult.errmsg);
  40. }
  41. HttpContext.Session.SetString("OpenId", openIdResult.openid);//进行登录
  42. //也可以使用FormsAuthentication等其他方法记录登录信息,如:
  43. //FormsAuthentication.SetAuthCookie(openIdResult.openid,false);
  44. return Redirect(returnUrl);
  45. }
  46. catch (Exception e)
  47. {
  48. return Content("错误:" + e.Message);
  49. }
  50. }
  51. }
  52. }