Я пробовал ответный разбор и outputCache промежуточное программное обеспечение в моем коде C#, без удачи. Моей последней попыткой было использование службы addmvc с nostore , установленным в True, и местоположение, установленное в responsecachelocation.none . Это тоже не работает. Как отключить кэширование в моем API?
Вот моя программа.
Код: Выделить всё
using TalkDeskAPI_WithReply;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddMvc(o => {
o.Filters.Add(new ResponseCacheAttribute { NoStore = true, Location = ResponseCacheLocation.None });
});
// hard coded connection string for development/testing
string ConnStr = "Data Source = xx.xx.xxx.xxx,xxxx; Initial Catalog = XXXX; TrustServerCertificate = True; User ID = XXXXXXX; Password = XXXXXXXX";
var app = builder.Build();
app.UseAuthorization();
// Middleware to validate apiKey - works and not relevant here
app.UseAPIKeyMiddleware();
app.UseResponseCaching();
using (SqlConnection connection = new SqlConnection(ConnStr))
{
SqlCommand command = new SqlCommand("dbo.Get_Data_For_API_Test_Data_3", connection);
command.CommandType = CommandType.StoredProcedure;
command.Connection.Open();
command.ExecuteNonQuery();
List result = new List();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Contact c = new Contact();
c.c_Id = (Int64)reader["c_Id"];
c.member_PhoneNumber = (string)reader["member_PhoneNumber"];
c.member_FirstName = (string)reader["member_FirstName"];
c.member_LastName = (string)reader["member_LastName"];
c.member_ID = (string)reader["member_ID"];
c.Message = (string)reader["message"];
result.Add(c);
}
}
command.Connection.Close();
command.Connection.Dispose();
// Get Contact Item
app.MapGet("/api/Contact", async () => result).CacheOutput (o =>
{
o.Expire(TimeSpan.FromMilliseconds(1));
o.NoCache();
});
app.Run();
}
< /code>
Вот мой код задачи сценария SSIS C#, который вызывает сторонний API, который запускает рабочий процесс, который запрашивает наш DB через мой API (код, указанный выше). Этот код работает, но был запрошен MJWills в комментариях: < /p>
#region Namespaces
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
using System.Collections.Generic;
#endregion
namespace ST_5c51b49b0eb04bbaa529180a116d1432
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
SendPost().GetAwaiter();
}
public async System.Threading.Tasks.Task SendPost()
{
try
{
string Auth = GetToken().GetAwaiter().GetResult();
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.talkdeskapp.com/flows/xxxxxxxxxxxxxx/interactions");
request.Headers.Add("Authorization", "Bearer " + Auth);
var content = new StringContent("{}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.Write(ex.InnerException.Message);
}
}
private async Task GetToken()
{
try
{
string AuthToken = "";
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
var client = new HttpClient();
Uri baseUri = new Uri("https://xxxxxxx.talkdeskid.com");
client.BaseAddress = baseUri;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
var collection = new List();
collection.Add(new KeyValuePair("grant_type", "client_credentials"));
var content = new FormUrlEncodedContent(collection);
string clientId = "xxxxxxxxxxxxxxxxxxxxxx";
string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var authenticationString = $"{clientId}:{clientSecret}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/oauth/token");
requestMessage.Headers.Add("Authorization","Basic " + base64EncodedAuthenticationString);
requestMessage.Content = content;
var response = await client.SendAsync(requestMessage);
dynamic tokenResponse = await response.Content.ReadAsStringAsync();
dynamic obj = JsonConvert.DeserializeObject(tokenResponse);
AuthToken = obj.access_token;
if (response.IsSuccessStatusCode)
{
return AuthToken;
}
else
{
Console.WriteLine("Failed Authorization");
return AuthToken;
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.Write(ex.InnerException.Message);
return "";
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... inimal-api