You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写ASP.NET C#测试用例:模拟50人同时调用同一进程并获各自结果

模拟50用户并发访问ASP.NET接口的C#测试用例

Hey there! Let's build a practical C# test that simulates 50 concurrent users hitting your ASP.NET endpoint, captures each request's outcome, and helps you validate how your process behaves under this load. Here's a step-by-step implementation:

1. Core Setup & Key Notes

First, a couple of critical points to avoid common pitfalls:

  • Reuse HttpClient: Never create a new HttpClient for each request—this leads to socket exhaustion. We'll use a static shared instance instead.
  • Track individual results: We need to capture success status, response content, and HTTP status code for every single request to analyze behavior.

2. Full Test Code Example

This code uses Task.WhenAll to fire off 50 requests simultaneously and collect all results once they complete:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

class ConcurrentApiLoadTest
{
    // Reuse a single HttpClient instance across all requests
    private static readonly HttpClient _httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        const int concurrentUserCount = 50;
        var requestTasks = new List<Task<(bool IsSuccess, string ResponseContent, int StatusCode)>>();

        // Spin up 50 concurrent request tasks
        for (int i = 0; i < concurrentUserCount; i++)
        {
            int requestIdentifier = i + 1; // Unique ID to track each request
            requestTasks.Add(SendApiRequestAsync(requestIdentifier));
        }

        // Wait for all requests to finish and gather results
        var allResults = await Task.WhenAll(requestTasks);

        // Print a summary of all outcomes
        Console.WriteLine("=== 50 Concurrent Request Results ===");
        foreach (var result in allResults)
        {
            string statusLabel = result.IsSuccess ? "✅ SUCCESS" : "❌ FAILED";
            Console.WriteLine($"{statusLabel} | Status Code: {result.StatusCode} | Response: {result.ResponseContent.Trim()}");
        }

        // Clean up resources when done
        _httpClient.Dispose();
    }

    private static async Task<(bool IsSuccess, string ResponseContent, int StatusCode)> SendApiRequestAsync(int requestId)
    {
        try
        {
            // Replace this with your actual ASP.NET endpoint URL
            string apiEndpoint = $"https://your-aspnet-api.com/api/your-process?requestId={requestId}";

            // For GET requests (swap to PostAsync if you need to send data)
            HttpResponseMessage response = await _httpClient.GetAsync(apiEndpoint);
            
            string responseBody = await response.Content.ReadAsStringAsync();

            return (response.IsSuccessStatusCode, responseBody, (int)response.StatusCode);
        }
        catch (Exception ex)
        {
            // Catch and report any errors (e.g., connection timeouts, DNS failures)
            return (false, $"Request {requestId} failed: {ex.Message}", 0);
        }
    }
}

3. Adaptations for Your Use Case

POST/PUT Requests

If your endpoint expects POST data, modify the SendApiRequestAsync method to send a payload:

// Example: Send JSON payload via POST
var requestPayload = new StringContent(
    "{\"userId\": 123, \"action\": \"process-data\"}",
    System.Text.Encoding.UTF8,
    "application/json"
);
HttpResponseMessage response = await _httpClient.PostAsync(apiEndpoint, requestPayload);

Timeout Configuration

If your process takes longer than the default HttpClient timeout (100 seconds), set a custom timeout:

_httpClient.Timeout = TimeSpan.FromMinutes(2); // Adjust based on your endpoint's expected latency

4. Additional Tips for Validating Process Behavior

  • Add Server-Side Logging: In your ASP.NET code, log details like request ID, thread ID, start/end time, and resource usage (CPU, memory) for each request. This lets you correlate test results with server behavior.
  • Test Edge Cases: Try running the test multiple times, adjust concurrent user counts, or simulate slow network conditions to stress-test your process further.
  • Monitor Metrics: Use tools like Windows Performance Monitor or ASP.NET's built-in metrics to track server health during the test (e.g., request queue length, active threads).

内容的提问来源于stack exchange,提问作者ismail bhinder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:47:18