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

如何调用同一服务器上其他项目的控制器函数实现网站自动发邮件?

Alright, let's break down how to call that co-hosted EmailController's Send method to get your auto-email functionality up and running. Since both projects live on the same server, we've got two solid approaches to choose from:

Calling the Co-Hosted Email API for Auto-Email Sending

First, let's recap what we're working with: you've got a POST endpoint in an EmailController that accepts a SendMailModel to trigger email sends. Here's how to hook into it from your website project:


This is the most flexible approach—even if you move the email project to a different server later, this code will only need a quick URL update.

Step 1: Set up HttpClient in your project

If you're using .NET Core/.NET 5+, add HttpClient to your dependency injection container for better performance and reusability:

// In Program.cs (or Startup.cs for older .NET Core versions)
builder.Services.AddHttpClient();

For older .NET Framework projects, you can instantiate HttpClient directly (just avoid creating a new instance every time you send an email).

Step 2: Prepare your email payload

Create a SendMailModel object that matches the one expected by the target controller—make sure property names and data types are identical to avoid serialization issues:

var autoMail = new SendMailModel
{
    SendingApp = "YourWebsiteName",
    SendTo = "user@example.com",
    Subject = "Auto-Generated Notification",
    Body = "This is the content of your automated email."
    // Add any other required fields from the model here
};

Step 3: Send the POST request

Use the local server URL (or virtual directory path) to hit the email endpoint. Example with injected HttpClient:

private readonly HttpClient _httpClient;

// Inject HttpClient via your service's constructor
public YourWebsiteEmailService(HttpClient httpClient)
{
    _httpClient = httpClient;
}

public async Task TriggerAutoEmail()
{
    var autoMail = new SendMailModel { /* populate fields as above */ };
    var response = await _httpClient.PostAsJsonAsync("http://localhost:5000/api/Email/Send", autoMail);
    
    // Handle success/error cases
    if (!response.IsSuccessStatusCode)
    {
        var errorDetails = await response.Content.ReadAsStringAsync();
        // Log the error or throw an exception based on your needs
        throw new InvalidOperationException($"Failed to send auto-email: {errorDetails}");
    }
}

Option 2: Direct Project Reference (Tight Coupling, Quick Win)

If both projects are in the same solution, you can skip HTTP calls entirely by referencing the email project directly.

Step 1: Add a project reference

Right-click your website project in Visual Studio → Add → Project Reference → Select the email API project.

Step 2: Call the controller method directly

Instantiate the EmailController and invoke its Send method. Note: You'll need to ensure the controller has access to its required config (like the senderEmail app setting) either via your website's config or explicit setup:

var emailController = new EmailController();
var autoMail = new SendMailModel { /* populate fields */ };
emailController.Send(autoMail);

⚠️ Heads up: This approach tightly couples your website to the email project. If you ever need to move the email service to another server, you'll have to rewrite this code. Only use this if you're certain the two projects will always stay co-hosted.


Critical Checks to Avoid Headaches

  • Verify the endpoint route: By default, Web API uses api/[controller]/[action], so the URL should be api/Email/Send unless custom routing is configured.
  • Match the SendMailModel exactly: Same namespace, property names, and data types—otherwise the HTTP request will fail to serialize correctly.
  • Enable loopback requests: Some hosting environments block server-to-server local requests. If you hit errors, check if loopback access is allowed for your server.
  • Confirm config settings: The email controller relies on senderEmail in its config—make sure that setting exists and is correct in the email project's web.config/appsettings.json.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:19:41