AuthController.cs 2.3 KB

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