【发布时间】:2019-06-09 13:57:41
【问题描述】:
我正在使用外部 Restful Api。我为 headers 值提供了授权密钥。当我尝试使用邮递员发送请求时,它返回 200 Ok 我在代码上使用相同的 API KEY。使用授权密钥使用 Restful Api 的正确方法是什么?
我已经为 ConfigureServices 和 Configure 配置了 Startup.cs。然后我使用 HttpClient 来使用 Restful Api。不知何故,我收到了 401 Unauthorized 响应。
Startup.cs 代码
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddAuthentication();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();
}
Services.cs 代码:
private static HttpClient _httpClient = new HttpClient();
public CRUDService()
{
_httpClient.BaseAddress = new Uri("https://api.deezer.com");
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-API_KEY", "081f0fca-1bca-4e8e-9a24-22ff2c3d462c");
_httpClient.Timeout = new TimeSpan(0, 0, 30);
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task Run()
{
await GetResource();
}
public async Task GetResource()
{
var response = await _httpClient.GetAsync("/v1/song/latest");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var movies = new List<Movie>();
if (response.Content.Headers.ContentType.MediaType == "application/json")
{
movies = JsonConvert.DeserializeObject<List<Movie>>(content);
}
}
【问题讨论】:
-
我真的希望那不是您的实际 API 密钥...
-
@MattOestreich 是的,没错。出于安全目的。对不起。您知道如何在 Startup.cs 中全局注册该 API 密钥,以便它可以通过应用程序访问吗?谢谢
-
您将使用 app.config/web.config 文件:stackoverflow.com/questions/5989736/…
-
ASP.NET Core 有一个完整的configuration 系统供 where 存储诸如 API 密钥之类的东西。 environment variable 可能是生产工作流的好地方(如果你在 Azure 中,Azure Key Vault)。
-
我建议通读Initiate HTTP requests,以了解如何有效地使用
HttpClient。
标签: c# asp.net-core-webapi asp.net-core-2.1