DOTNETCODE Telegram 3051
قابلیت HTTP Headers در C# چطوریه؟

امروز می‌خوایم یه موضوع ساده ولی فوق‌العاده کاربردی رو با هم مرور کنیم: کار با هدرهای HTTP در C# با استفاده از HttpClient.

هدرها (Headers) بخش مهمی از هر درخواست و پاسخ HTTP هستن و اطلاعات اضافی مثل کلیدهای دسترسی (API Key)، نوع محتوا (Content-Type) و... رو منتقل می‌کنن. توی این پست ۳ سناریوی اصلی رو با هم می‌بینیم:

۱. اضافه کردن هدر به تمام درخواست‌ها (Default Headers)

وقتی یه سری اطلاعات مثل ApiKey یا Authorization Token باید توی تمام درخواست‌هایی که به یک سرور خاص ارسال میشه وجود داشته باشه، بهترین راه استفاده از DefaultRequestHeaders هست. اینطوری یک بار هدر رو تنظیم می‌کنید و برای همیشه (تا زمانی که اون HttpClient زنده است) استفاده میشه.

مثال:
// Create a single instance of HttpClient for your application
HttpClient client = new();

// Add an API Key that will be sent with EVERY request made by this client
client.DefaultRequestHeaders.Add("ApiKey", "YourSuperSecretKeyFromApi");

// Now, any request like client.GetAsync, client.PostAsync, etc. will have this header.
var response = await client.GetAsync("https://api.example.com/data");

۲. اضافه کردن هدر فقط به یک درخواست خاص
گاهی وقت‌ها لازمه یک هدر رو فقط برای یک درخواست خاص ارسال کنید. مثلاً یک هدر برای ردیابی (tracing) یا کشینگ. در این حالت، هدر رو مستقیماً به شیء HttpRequestMessage اضافه می‌کنیم.

مثال:
HttpClient client = new();
var url = "https://api.example.com/data";

// Create a specific request message
HttpRequestMessage request = new(HttpMethod.Get, url);

// Add a header ONLY for this specific request
request.Headers.Add("X-Custom-ID", "some-unique-value-123");

// Send the request
HttpResponseMessage response = await client.SendAsync(request);

۳. خوندن هدر از پاسخ سرور (Response)
بعد از اینکه درخواستی رو ارسال کردید، سرور در پاسخ (Response) ممکنه هدرهای مهمی رو برگردونه. مثلاً اطلاعات مربوط به محدودیت تعداد درخواست (Rate Limiting) یا جزئیات صفحه‌بندی (Pagination). برای خوندن این هدرها به شکل ایمن (که اگر هدر وجود نداشت برنامه کرش نکنه)، از متد TryGetValues استفاده می‌کنیم.

مثال:
// Assuming 'response' is the HttpResponseMessage from the server
string apiKey = string.Empty;

// Try to get the value of the "ApiKey" header
if (response.Headers.TryGetValues("ApiKey", out var keyValues))
{
// If the header exists, get the first value.
// keyValues is an IEnumerable<string>
apiKey = keyValues.FirstOrDefault();
}

Console.WriteLine($"API Key from response: {apiKey ?? "Not Found"}");

💡 نکته کلیدی: از DefaultRequestHeaders برای مقادیر ثابت مثل کلید API و از request.Headers برای مقادیر داینامیک که در هر درخواست ممکنه تغییر کنن استفاده کنید تا کدتون تمیزتر و بهینه‌تر باشه.

🎺برای یادگیری بیشتر و دریافت مطالب مفید در زمینه .NET و برنامه‌نویسی، به کانال ما بپیوندید!

📚💻 @dotnetcode 🖥👨‍💻
Please open Telegram to view this post
VIEW IN TELEGRAM
8👏4👍1🎉1



tgoop.com/dotnetcode/3051
Create:
Last Update:

قابلیت HTTP Headers در C# چطوریه؟

امروز می‌خوایم یه موضوع ساده ولی فوق‌العاده کاربردی رو با هم مرور کنیم: کار با هدرهای HTTP در C# با استفاده از HttpClient.

هدرها (Headers) بخش مهمی از هر درخواست و پاسخ HTTP هستن و اطلاعات اضافی مثل کلیدهای دسترسی (API Key)، نوع محتوا (Content-Type) و... رو منتقل می‌کنن. توی این پست ۳ سناریوی اصلی رو با هم می‌بینیم:

۱. اضافه کردن هدر به تمام درخواست‌ها (Default Headers)

وقتی یه سری اطلاعات مثل ApiKey یا Authorization Token باید توی تمام درخواست‌هایی که به یک سرور خاص ارسال میشه وجود داشته باشه، بهترین راه استفاده از DefaultRequestHeaders هست. اینطوری یک بار هدر رو تنظیم می‌کنید و برای همیشه (تا زمانی که اون HttpClient زنده است) استفاده میشه.

مثال:

// Create a single instance of HttpClient for your application
HttpClient client = new();

// Add an API Key that will be sent with EVERY request made by this client
client.DefaultRequestHeaders.Add("ApiKey", "YourSuperSecretKeyFromApi");

// Now, any request like client.GetAsync, client.PostAsync, etc. will have this header.
var response = await client.GetAsync("https://api.example.com/data");

۲. اضافه کردن هدر فقط به یک درخواست خاص
گاهی وقت‌ها لازمه یک هدر رو فقط برای یک درخواست خاص ارسال کنید. مثلاً یک هدر برای ردیابی (tracing) یا کشینگ. در این حالت، هدر رو مستقیماً به شیء HttpRequestMessage اضافه می‌کنیم.

مثال:
HttpClient client = new();
var url = "https://api.example.com/data";

// Create a specific request message
HttpRequestMessage request = new(HttpMethod.Get, url);

// Add a header ONLY for this specific request
request.Headers.Add("X-Custom-ID", "some-unique-value-123");

// Send the request
HttpResponseMessage response = await client.SendAsync(request);

۳. خوندن هدر از پاسخ سرور (Response)
بعد از اینکه درخواستی رو ارسال کردید، سرور در پاسخ (Response) ممکنه هدرهای مهمی رو برگردونه. مثلاً اطلاعات مربوط به محدودیت تعداد درخواست (Rate Limiting) یا جزئیات صفحه‌بندی (Pagination). برای خوندن این هدرها به شکل ایمن (که اگر هدر وجود نداشت برنامه کرش نکنه)، از متد TryGetValues استفاده می‌کنیم.

مثال:
// Assuming 'response' is the HttpResponseMessage from the server
string apiKey = string.Empty;

// Try to get the value of the "ApiKey" header
if (response.Headers.TryGetValues("ApiKey", out var keyValues))
{
// If the header exists, get the first value.
// keyValues is an IEnumerable<string>
apiKey = keyValues.FirstOrDefault();
}

Console.WriteLine($"API Key from response: {apiKey ?? "Not Found"}");

💡 نکته کلیدی: از DefaultRequestHeaders برای مقادیر ثابت مثل کلید API و از request.Headers برای مقادیر داینامیک که در هر درخواست ممکنه تغییر کنن استفاده کنید تا کدتون تمیزتر و بهینه‌تر باشه.

🎺برای یادگیری بیشتر و دریافت مطالب مفید در زمینه .NET و برنامه‌نویسی، به کانال ما بپیوندید!

📚💻 @dotnetcode 🖥👨‍💻

BY DotNet | دات نت




Share with your friend now:
tgoop.com/dotnetcode/3051

View MORE
Open in Telegram


Telegram News

Date: |

Telegram offers a powerful toolset that allows businesses to create and manage channels, groups, and bots to broadcast messages, engage in conversations, and offer reliable customer support via bots. 1What is Telegram Channels? Telegram channels enable users to broadcast messages to multiple users simultaneously. Like on social media, users need to subscribe to your channel to get access to your content published by one or more administrators. Telegram Channels requirements & features Among the requests, the Brazilian electoral Court wanted to know if they could obtain data on the origins of malicious content posted on the platform. According to the TSE, this would enable the authorities to track false content and identify the user responsible for publishing it in the first place.
from us


Telegram DotNet | دات نت
FROM American