【发布时间】:2021-06-29 11:46:24
【问题描述】:
我目前正在开发 .NET Framework 4.6 下的 Web API 项目。 它使用不记名令牌身份验证。 但我注意到控制器动作的响应时间问题。即使 Web API 托管在本地 IIS Express 上,响应时间也相当长。即日志记录(基于 IActionFilter)显示控制器的执行时间为 20 毫秒,而 Postman 显示响应时间约为 3 或 4 秒。 造成这种差异的原因是什么?
采取了两个步骤:
- 使用扩展方法 SuppressDefaultHostAuthentication 以避免默认身份验证可能产生的副作用。遗憾的是没有任何改进。
- 要添加依赖注入,默认实现的接口最初缺少,并且在 Web API 启动时引发了相应的异常。即我添加了
.RegisterType() .RegisterType ()。遗憾的是没有任何改进。
请在下面找到 WebApiConfig.cs 和 Startup.cs 文件的内容
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MapHttpAttributeRoutes();
//config.SuppressDefaultHostAuthentication();
// TODO: check the necessity to use Storages here, why not on services level
var container = new UnityContainer();
/*some dependecies mapping here*/
container.AddExtension(new Diagnostic());
config.DependencyResolver = new UnityResolver(container);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new ApiAuthenticationFilter(container.Resolve<BLI.IUserSessionManagement>()));
config.Filters.Add(new ApiAuthorizationFilter(container.Resolve<BLI.IAuthorizer>(), container.Resolve<BET.IAuthLogger>()));
config.Filters.Add(new LoggingFilterAttribute(new BET.ControllerTracer()));
}
Startup.cs 文件
public void Configuration(IAppBuilder app)
{
//TODO : try to find better solution
BackEnd.WebAPI.Models.UnityResolver ur = (BackEnd.WebAPI.Models.UnityResolver)System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver;
Type providerType = Type.GetType("Microsoft.Owin.Security.OAuth.IOAuthAuthorizationServerProvider, Microsoft.Owin.Security.OAuth", true);
ApiOAuthAuthorizationServerProvider serverProvider = (ApiOAuthAuthorizationServerProvider)ur.GetService(providerType);
//
OAuthAuthorizationServerOptions oAuthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/auth"),
Provider = serverProvider,
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
AllowInsecureHttp = true
};
app.UseOAuthAuthorizationServer(oAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
额外采取的行动:
- 禁用身份验证和授权过滤器。未检测到任何改善。
- 在 Azure 上执行相同的测试。相同的情况:基于操作过滤器的日志记录报告了控制器操作的高性能,但客户端接收到的响应与在本地 IIS Express 上一样存在基本延迟
【问题讨论】:
标签: c# performance controller