我有一个面向 .NET 4.8 的 ASP.NET Web API 项目。
在顶部,它添加了 ASP.NET Core 配置服务
Startup.cs
。
它有
Startup.cs
、配置服务、.NET 4.8 和 app.config
。
我在门户上创建了一个应用程序洞察资源。安装了 Microsoft.ApplicationInsights.AspNetCore
nuget 包,将门户 AI 资源检测密钥添加到 app.config
。
然后我使用 postman 向 API 发送请求,期望能够在 App Insights 上看到请求和分析器。运气不好!
Startup.cs
/*
* API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using System.Linq;
using Microsoft.ApplicationInsights.Extensibility;
using System.Web.Configuration;
namespace MyNamespace
{
/// <summary>
/// Startup
/// </summary>
public class Startup
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// The application configuration.
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder
.WithExposedHeaders("WV-Token")
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
TelemetryConfiguration.Active.InstrumentationKey = WebConfigurationManager.AppSettings["InstrumentationKey"];
services.AddApplicationInsightsTelemetry(Configuration);
var secretKey = System.Configuration.ConfigurationManager.AppSettings["TokenSecret"];
//var issuer = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
//var audience = System.Configuration.ConfigurationManager.AppSettings["Audience"];
services
.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = System.Configuration.ConfigurationManager.AppSettings["Issuer"],
ValidAudience = System.Configuration.ConfigurationManager.AppSettings["Audience"],
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)),
};
});
services
.AddMvc(opts => {
opts.InputFormatters.Insert(0, new InputFormatterStream());
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Converters.Add(new StringEnumConverter
{
CamelCaseText = true
});
});
services
.AddSwaggerGen(c =>
{
c.SwaggerDoc("1.0.0", new Info
{
Version = "1.0.0",
Title = "API",
Description = "API (ASP.NET Core 2.1)",
TermsOfService = ""
});
c.CustomSchemaIds(type => type.FriendlyId(true));
c.DescribeAllEnumsAsStrings();
c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{Assembly.GetEntryAssembly().GetName().Name}.xml");
c.OperationFilter<GeneratePathParamsValidationFilter>();
});
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHttpsRedirection();
app
.UseCors()
.UseMvc()
.UseDefaultFiles()
.UseStaticFiles()
.UseSwagger(c =>
{
c.RouteTemplate = "swagger/{documentName}/openapi.json";
})
.UseSwaggerUI(c =>
{
//TODO: Either use the SwaggerGen generated Swagger contract (generated from C# classes)
c.SwaggerEndpoint("/swagger/1.0.0/openapi.json", "API");
//TODO: Or alternatively use the original Swagger contract that's included in the static files
// c.SwaggerEndpoint("/openapi-original.json", "API Original");
});
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
}
}
}
应用程序配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="EFConnstringKey" value=""/>
<!-- settings below here are global -->
<add key="InstrumentationKey" value="27bafd8b-7e18-4985-87eb-92e8fb014450"/>
<add key="SmtpServer" value=""/>
<add key="TokenSecret" value=" "/>
<add key="Issuer" value=" "/>
<add key="Audience" value=" "/>
<add key=" " value=" "/>
<add key=" " value=" "/>
</appSettings>
<connectionStrings>
<!-- leaving as sample, not used in code. 'connectionString' value is stored in connstring manager after replacing """ with "'" -->
</connectionStrings>
<runtime>
<gcServer enabled="true"/>
</runtime>
</configuration>
仅几点。
services.AddApplicationInsightsTelemetry(Configuration);
传入Configuration对象有什么原因吗?通常,如果需要,我会传入 ApplicationInsightsServiceOptions() 类型的对象。否则我不会使用任何参数。
builder.Services.AddServiceProfiler()
您可能还需要添加对 Microsoft.ApplicationInsights.Profiler.AspNetCore Nuget 包的引用。