已要求我使用WebApi 2.1设置服务,该服务将能够接受MailMessage对象作为参数,发送该邮件消息,并记录该邮件已发送。
我已根据Microsoft的以下示例对我的尝试进行了模式化: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/bson-support-in-web-api-21
这是我控制器中的动作:
[HttpPost]
[Route("api/Email/SendMailMessage")]
public async Task SendMailMessage(System.Net.Mail.MailMessage msg)
{
await _emailSender.SendMailMessageAsync(msg);
}
这是调用API的测试方法:
public async void TestMailMessage()
{
MailMessage msg = new MailMessage();
// snip details of msg population for brevity
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:40353/");
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var result = await client.PostAsync("api/Email/SendMailMessage", msg, bsonFormatter);
}
}
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMvc().AddBsonSerializerFormatters();
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.AddTransient<IEmailSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
我遇到的问题是MailMessage对象在服务器上作为null传入。
或者,我尝试将对象序列化为字节,但是由于MailMessage类不可序列化,因此失败了。