I need to break the pipeline and return response immediately if condition triggered.I need to stop request before proceed to other middlewares and code itself .
How can I achieve that , I want to check this header key for security purposes .
public async Task Invoke(HttpContext httpContext,ILogger logger)
{
try
{
var request = httpContext.Request;
var headerValue = request.Headers.TryGetValue("security", out var contentType);
if (!headerValue || contentType != "secret key")
{
httpContext.Response.StatusCode = 400;
httpContext.Response.Body = null; // maybe add a error message
}
}
catch (Exception ex)
{
await _next(httpContext);
}
}
}
using Discord;
using Discord.WebSocket;
using RestSharp;
using Newtonsoft.Json;
using System.Net;
namespace DiscordBot.Service;
public class OpenAiService
{
private const string OpenAiApiKey = "OPENAIKEY";
private const string ChatGptApiUrl = "https://api.openai.com/v1/completions";
private const string DalleApiUrl = "https://api.openai.com/v1/images/generations";
/// <param name="message"></param>
internal static async Task<Tuple<bool, string>> ChatGpt(SocketMessage message)
{
try
{
if (string.IsNullOrWhiteSpace(message.Content.Substring(5)))
{
await message.Channel.SendMessageAsync("The message content is empty. Please provide a prompt for the ChatGPT API.");
return new Tuple<bool, string>(false, "The message content is empty.");
}
// Create a new RestClient instance
var client = new RestClient(ChatGptApiUrl);
// Create a new RestRequest instance
var request = new RestSharp.RestRequest("", Method.Post);
// Set the request headers
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {OpenAiApiKey}");
// Create the request data
var data = new
{
// The prompt is everything after the !chat command
model = "text-davinci-003",
prompt = message.Content.Substring(5),
max_tokens = 256
};
var jsonData = JsonConvert.SerializeObject(data);
// Add the request data to the request body
request.AddJsonBody(jsonData);
// Send the request and get the response
var response = await client.ExecuteAsync(request);
// Holds the response from the API.
string responseText;
var success = true;
// Check the status code of the response
if (response.Content != null && response.StatusCode == HttpStatusCode.OK)
{
// Get the response text from the API
responseText = JsonConvert.DeserializeObject<dynamic>(response.Content)?["choices"][0]["text"] ??
"Could not deserialize response from ChatGPT Api!";
}
else
{
// Get the ErrorMessage from the API
responseText = response.ErrorMessage ?? string.Empty;
success = false;
}
// Send the response to the Discord chat
await message.Channel.SendMessageAsync(responseText);
return new Tuple<bool, string>(success, responseText);
}
catch (Exception ex)
{
// Log the exception or handle it in another way
Console.WriteLine(ex.Message);
return new Tuple<bool, string>(false, "An error occurred while sending the request to the ChatGPT API");
}
}
/// <summary>
/// The method uses the RestClient class to send a request to the Dall-E API, passing the user's message as the
/// prompt and sends an image to the Chat
/// </summary>
/// <param name="message"></param>
/// <returns>Boolean indicating whether the request was successful</returns>
internal static async Task<Tuple<bool, string>> DallE(SocketMessage message)
{
try
{
if (string.IsNullOrWhiteSpace(message.Content.Substring(5)))
{
await message.Channel.SendMessageAsync("The message content is empty. Please provide a prompt for the ChatGPT API.");
return new Tuple<bool, string>(false, "The message content is empty.");
}
// Create a new RestClient instance
var client = new RestClient(DalleApiUrl);
// Create a new RestRequest instance
var request = new RestSharp.RestRequest("", Method.Post);
// Set the request headers
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {OpenAiApiKey}");
// Create the request data
var data = new
{
// The prompt is everything after the !image command
model = "image-alpha-001",
prompt = message.Content.Substring(6),
n = 1,
size = "1024x1024"
};
var jsonData = JsonConvert.SerializeObject(data);
// Add the request data to the request body
request.AddJsonBody(jsonData);
// Send the request and get the response
var response = await client.ExecuteAsync(request);
// Holds the response from the API.
string responseText;
var success = false;
// Check the status code of the response
if (response.Content != null && response.StatusCode == HttpStatusCode.OK)
{
// Get the image URL from the API response
var imageUrl = JsonConvert.DeserializeObject<dynamic>(response.Content)?["data"][0]["url"];
responseText = $"Here is the generated image: {imageUrl}";
success = true;
}
else
{
// Get the ErrorMessage from the API
responseText = response.ErrorMessage ?? string.Empty;
}
// Send the response to the Discord chat
await message.Channel.SendMessageAsync(responseText);
return new Tuple<bool, string>(success, responseText);
}
catch (Exception ex)
{
// Log the exception or handle it in another way
Console.WriteLine(ex.Message);
return new Tuple<bool, string>(false, "An error occurred while sending the request to the Dall-e API");
}
}
}
public class Program
{
private const string DiscordToken = "BOTTOKEN";
private static void Main()
{
MainAsync().GetAwaiter().GetResult();
}
public static async Task MainAsync()
{
//Creates a config with specified gateway intents
var config = new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
};
// Create a new Discord client
var client = new DiscordSocketClient(config);
// Log messages to the console
client.Log += Log;
// Handle messages received
client.MessageReceived += HandleCommand;
// Login to Discord
await client.LoginAsync(TokenType.Bot, DiscordToken);
// Start the client
await client.StartAsync();
// Block this program until it is closed
await Task.Delay(-1);
}
/// <summary>
/// This method is called whenever a message is received
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private static async Task HandleCommand(SocketMessage message)
{
var success = true;
var responseText = string.Empty;
await Log(new LogMessage(LogSeverity.Info, nameof(HandleCommand),
"New Message incoming..."));
// Check if the message starts with one of these commands
switch (message.Content)
{
case { } chat when chat.StartsWith("!chat"):
await Log(new LogMessage(LogSeverity.Info, nameof(HandleCommand),
"Recived !chat command: " + message.Content));
(success, responseText) = await OpenAiService.ChatGpt(message);
break;
case { } image when image.StartsWith("!image"):
await Log(new LogMessage(LogSeverity.Info, nameof(HandleCommand),
"Recived !image command: " + message.Content));
(success, responseText) = await OpenAiService.DallE(message);
break;
default:
await Log(new LogMessage(LogSeverity.Info, nameof(HandleCommand),
"No command found, normal message"));
break;
}
if (!success)
await Log(new LogMessage(LogSeverity.Warning, nameof(HandleCommand),
"Error with one of the request to the Apis!"));
if (!string.IsNullOrEmpty(responseText))
await Log(new LogMessage(LogSeverity.Info, nameof(HandleCommand),
"Respone: " + responseText));
}
/// <summary>
/// This method logs messages to the console
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
private static Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
}
Here is my code that does not contain errors according to the compiler but causes errors in the console:
15:58:09 Discord Discord.Net v3.9.0 (API v10)
15:58:09 Gateway Connecting
15:58:11 Gateway You're using the GuildScheduledEvents gateway intent without listening to any events related to that intent, consider removing the intent from your config.
15:58:11 Gateway You're using the GuildInvites gateway intent without listening to any events related to that intent, consider removing the intent from your config.
15:58:11 Gateway Connected
15:58:11 Gateway Ready
15:58:36 HandleComma New Message incoming...
15:58:36 HandleComma No command found, normal message
15:58:55 HandleComma New Message incoming...
15:58:55 HandleComma Recived !chat command: !chat explain me quantum physic in simple terms
Argument cannot be blank. (Parameter 'Content')
15:58:55 HandleComma Error with one of the request to the Apis!
15:58:55 HandleComma Respone: An error occurred while sending the request to the ChatGPT API
So I asked ChatGPT, who returned my code without modification.
Then I looked for help on this:
You're using the GuildScheduledEvents gateway intent without listening to any events related to that intent, consider removing the intent from your config. You're using the GuildInvites gateway intent without listening to any events related to that intent, consider removing the intent from your config.
I couldn't find anything except this: Events in Discord.Net
I would need help and am at your disposal for any further information
I am using Microsoft Bot framework (SDK v3) to create a QnA bot. While calling the QnAMaker API, the execution gets stuck at HttpCleint.SendAsync.
I have tried calling ConfigureAwait(false) on all the async calls.
I have tried adding .Result at end of function calls.
Both doesn't seem to work.
[Serializable]
public class QnAMakerService
{
private string qnaServiceHostName;
private string knowledgeBaseId;
private string endpointKey;
public QnAMakerService()
{
qnaServiceHostName = "foo";
knowledgeBaseId = "bar";
endpointKey = "foo";
}
async Task<string> Post(string uri, string body)
{
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "EndpointKey " + endpointKey);
var response = await client.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
public async Task<string> GetAnswer(string question)
{
string uri = qnaServiceHostName + "/qnamaker/knowledgebases/" + knowledgeBaseId + "/generateAnswer";
string questionJSON = #"{'question': '" + question + "'}";
var response = await Post(uri, questionJSON);
var answers = JsonConvert.DeserializeObject<QnAAnswer>(response);
if (answers.answers.Count > 0)
{
return answers.answers[0].answer;
}
else
{
return "No good match found.";
}
}
}
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
///
QnAMakerService qna = new QnAMakerService();
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
var q = await qna.GetAnswer(activity.Text);
// return our reply to the user
Activity reply = activity.CreateReply($"{q}");
connector.Conversations.ReplyToActivity(reply);
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
}
The execution stops after the SendAsync call with a 500 internal server error excception.
I think the asynchonous code is getting blocked somewhere, but I don't know where.
EDIT : The same block of code(to call the API) works if I try it in a console application.
I would like to return a 422 Response from my API which includes as much of the data model that I can. I've created a method in our BaseRepository where we pass in the data, and an optional message, to return as a 422.
protected IHttpActionResult Create422Response<TData>(
TData data,
string message = "Resource validation failed."
)
{
var response = new ResponseObject<TData>(data)
{
Status = "Failure",
Message = message
};
return Content((HttpStatusCode)422, response);
}
On the client side, I'm catching the response like so:
var response = await _orderApiClient.ShowOrderForApproval(id);
if (response.StatusCode == (HttpStatusCode)422)
{
Logger.LogWarning(response.Content);
var responseJson = JObject.Parse(response.Content);
ProcessValidationErrorsFromResponse(response);
}
When I look at the value of response.Content, I see that the JSON is truncated.
If I pass the same data object through an OK response it works.
protected IHttpActionResult CreateOkResponse<TData>(TData data, string message = "Call was successful")
{
var response = new ResponseObject<TData>(data)
{
Status = "Success",
Message = message
};
return Ok(response);
}
Why would the 422 truncate the data? Could there be something else going on?
UPDATE:
Here's what ShowOrderForApproval does:
public async Task<IRestResponse> ShowOrderForApproval(int id)
{
var request = new RestRequest("/api/orders/{id}/approve/")
{
Method = Method.GET,
RequestFormat = DataFormat.Json
};
request.AddUrlSegment("id", id.ToString());
return await RsClient.SendRequestAsync(request, new HttpContextWrapper(HttpContext.Current));
}
RsClient.SendRequestAsync is:
public static Task<IRestResponse> SendRequestAsync(RestRequest request, HttpContextBase context)
{
if (_client == null)
{
_client = Connect();
}
//If null, this is coming from the CI API and we've stored the value in the originating request header
if (context.Session == null)
{
var authHeaderValue = context.Request.Headers["Authorization"];
request.AddHeader("Authorization", "Bearer " + authHeaderValue);
}
else
{
var sessionTokenName = ConfigurationManager.AppSettings["SessionTokenName"];
request.AddHeader("Authorization", "Bearer " + context.Session[sessionTokenName]);
}
return Task.FromResult(_client.Execute(request));
}
Update 2:
Okay, more updates. Using Postman I can get all the data with a 422. Our RsClient is using RestSharp.
I wrote simple method for getting data from (online) REST Service:
public async Task<Object> GetTask()
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://111.111.111.111:8080/");
HttpResponseMessage result = await client.GetAsync("ABC/CDE/getsomeinfo");
if (result.IsSuccessStatusCode)
{
//Deserialize
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error" + ex);
}
return null;
}
Whenever i run this on UWP i'm getting catch exception:
The text associated with this error code could not be found.
A connection with the server could not be established
HResult 2147012867
Im trying to connect my client with restapi in internal network. In forms same code is working properly.
Try this
HttpResponseMessage response;
public async Task<string> webserviceResponse(string HttpMethod)
{
// check internet connection is available or not
if (NetworkInterface.GetIsNetworkAvailable() == true)
{
// CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
HttpClient client = new HttpClient();
MultipartFormDataContent mfdc = new MultipartFormDataContent();
mfdc.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
string GenrateUrl = "your url";
if (HttpMethod == "POST")
{
response = await client.PostAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "PUT")
{
response = await client.PutAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "GET")
{
response = await client.GetAsync(GenrateUrl);
}
var respon = await response.Content.ReadAsStringAsync();
string convert_response = respon.ToString();
return convert_response;
}
else
{
return "0";
}
}