コード例 #1
0
        /// <summary>
        /// 申请友链
        /// </summary>
        /// <param name="links"></param>
        /// <returns></returns>
        public async Task <ActionResult> Apply(Links links)
        {
            if (!links.Url.MatchUrl())
            {
                return(ResultData(null, false, "添加失败!链接非法!"));
            }

            var host = new Uri(links.Url).Host;

            if (LinksService.Any(l => l.Url.Contains(host)))
            {
                return(ResultData(null, false, "添加失败!检测到您的网站已经是本站的友情链接了!"));
            }

            Uri uri = new Uri(links.Url);

            using (HttpClient client = new HttpClient()
            {
                BaseAddress = uri,
                Timeout = TimeSpan.FromSeconds(10)
            })
            {
                client.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0"));
                client.DefaultRequestHeaders.Referrer = new Uri(Request.Scheme + "://" + Request.Host.ToString());
                return(await await client.GetAsync(uri.PathAndQuery).ContinueWith(async t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        return ResultData(null, false, "添加失败!检测到您的网站疑似挂了,或者连接到你网站的时候超时,请检查下!");
                    }

                    var res = await t;
                    if (res.IsSuccessStatusCode)
                    {
                        var s = await res.Content.ReadAsStringAsync();
                        if (s.Contains(CommonHelper.SystemSettings["Domain"]))
                        {
                            var entry = LinksService.GetFirstEntity(l => l.Url.Equals(links.Url));
                            bool b;
                            if (entry is null)
                            {
                                b = LinksService.AddEntitySaved(links) != null;
                            }
                            else
                            {
                                entry.Url = links.Url;
                                entry.Except = links.Except;
                                entry.Name = links.Name;
                                entry.Recommend = links.Recommend;
                                b = LinksService.UpdateEntitySaved(entry);
                            }

                            return ResultData(null, b, b ? "添加成功!这可能有一定的延迟,如果没有看到您的链接,请稍等几分钟后刷新页面即可,如有疑问,请联系站长。" : "添加失败!这可能是由于网站服务器内部发生了错误,如有疑问,请联系站长。");
                        }

                        return ResultData(null, false, $"添加失败!检测到您的网站上未将本站设置成友情链接,请先将本站主域名:{CommonHelper.SystemSettings["Domain"]}在您的网站设置为友情链接,并且能够展示后,再次尝试添加即可!");
                    }

                    return ResultData(null, false, "添加失败!检测到您的网站疑似挂了!返回状态码为:" + res.StatusCode);
                }));
            }
        }