Ejemplo n.º 1
0
        /// <summary>
        /// 检查用户登录状态,并以异步的方式请请求传送给下一个Http Request Handler
        /// </summary>
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Method == HttpMethod.Options)
            {
                return(Task.Run <HttpResponseMessage>(() =>
                {
                    var resp = new HttpResponseMessage();
                    resp.Content = new StringContent("");
                    //resp.Content.Headers.Add("Access-Control-Allow-Origin", GetHeaderByKey(request, "Origin"));
                    resp.Content.Headers.Add("Access-Control-Allow-Origin", "*");
                    resp.Content.Headers.Add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                    resp.Content.Headers.Add("Access-Control-Allow-Headers", "token,Content-Type,X-Requested-With");
                    return resp;
                }));
            }

            try
            {
                lock (Locker)
                {
                    // check token except  register & login & resetpassword
                    if (request.RequestUri != null && IsNeededTokenApis(request.RequestUri.ToString()))
                    {
                        // 获取request中的token
                        var token = GetHeaderByKey(request, "token");
                        ApiWorkContext.Instance().Token = token;

                        if (string.IsNullOrEmpty(token) || !this.UserTokenService.IsVaild(token))
                        {
                            throw new InvalidCastException("Invalid token");
                        }
                        else
                        {
                            ApiWorkContext.Instance().User = UserTokenService.GetMemberByToken(token);
                        }
                    }
                }
            }
            catch (InvalidCastException ex)
            {
                return(Task.Run <HttpResponseMessage>(() =>
                {
                    return GenerateResponse(request, HttpStatusCode.Unauthorized, "Invalid token", ex.Message);
                }));
            }

            var result = base.SendAsync(request, cancellationToken);

            //if (result.Result != null)
            //{
            //    if (result.Result.StatusCode == HttpStatusCode.NotFound)
            //    {
            //        return Task.Run<HttpResponseMessage>(() =>
            //           {
            //               return GenerateResponse(request, HttpStatusCode.NotFound, "The requested resource is not found", null);
            //           });
            //    }
            //}

            return(result);
        }
Ejemplo n.º 2
0
 public BaseController()
 {
     this.Token  = ApiWorkContext.Instance().Token;
     this.Member = ApiWorkContext.Instance().User;
 }