"
utf-8
"
/>
<meta name=
"
viewport
"
content=
"
width=device-width, initial-scale=1.0
"
/>
<link rel=
"
icon
"
type=
"
image/x-icon
"
href=
"
#
"
/>
<title>@ViewData[
"
Title
"
] - WebApplicationDemo</title>
<meta name=
"
keywords
"
content=
""
>
<meta name=
"
description
"
content=
""
>
<meta name=
"
author
"
content=
"
Lio.Huang
"
>
</head>
<div style=
"
background-color:#808080;height:200px;
"
>
@RenderBody()
</body>
</html>
HomeController
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplicationDemo.Controllers
public class HomeController : Controller
public IActionResult Index()
return View();
Index.cshtml
<h1>Hi, I'm index page.</h1>
最简单不过的代码,然后启动项目,无意中就发现了,过程中发生了两次请求:
再新增一个控制器测试仍然是如此。
Debug
试想第二次请求发生了什么?加入一个请求统计的接口,拦截第二次请求。开撸:
public interface IRequestStat
int RequestNum { get; }
/// <summary>
/// 是否跳转
/// </summary>
/// <returns></returns>
bool Redirect();
/// <summary>
/// 请求次数累计
/// </summary>
void Add();
public class RequestStat : IRequestStat
public int RequestNum { get; private set; }
public RequestStat()
RequestNum = 1;
public void Add()
RequestNum++;
public bool Redirect()
return RequestNum == 2;
public class HomeController : Controller
private readonly IRequestStat request;
public HomeController(IRequestStat request)
this.request = request;
public IActionResult Index()
if (request.Redirect())
return Redirect("https://www.baidu.com/");
request.Add();
return View();
当第二次请求时候,重定向到百度网。
然后在Startup中注册为单例:
public void ConfigureServices(IServiceCollection services)
services.AddMvc();
services.AddSingleton<IRequestStat, RequestStat>();
发现它并没有跳转到百度网,但是也发现了"Bug"所在,favicon.ico是来自百度的。
第二次请求,其实浏览器是请求favicon.ico的tab图标文件。
如果页面没有提供favicon.ico时会从请求里尝试获取,但在生产过程中,Action是带有业务逻辑,我们肯定是不希望莫名其妙的被触发一次。
在_Layout.cshtml中把favicon.ico加上即可
<!DOCTYPE html>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<title>@ViewData["Title"] - WebApplicationDemo</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="author" content="Lio.Huang">
</head>
<div style="background-color:#808080;height:200px;">
@RenderBody()
</body>
</html>
真是一不小心就掉坑了,记录一下爬坑日志,一步一个 脚印 坑。