C# 使用 POST 方法将 ActionResult 更改为 IHttpActionResult

C# Change ActionResult to IHttpActionResult using POST method

我这里有一个代码,它实际上将 HTML 转换为 PDF 并将其发送到电子邮件,但它在 ActionResult 中:

public ActionResult Index()
{
    ViewBag.Title = "Home Page";

    var coverHtml = RenderRazorViewToString("~/Views/Home/Test.cshtml", null);
    var htmlContent = RenderRazorViewToString( "~/Views/Home/Test2.cshtml", null);
    string path = HttpContext.Server.MapPath("~/Content/PDF/html-string.pdf");
    PDFGenerator.CreatePdf(coverHtml, htmlContent, path);


    //PDFGenerator.CreatePdfFromURL("https://www.google.com", path);
    EmailHelper.SendMail("myemail@domain.com", "Test", "HAHA", path);

    return View();
}

我想将其转换为 api 格式 (api/SendPDF),使用 POST 以及内容 ID 和将要发送到的电子邮件地址,但我不确定怎么做,因为我对 MVC 和 Web API 很陌生。感谢对此的一些帮助。

首先创建一个class 例如。 Information.cs

public class Information{
    public int ContentId {get; set;}
    public string Email {get; set;}
}

在API控制器中,

[HttpPost]
public HttpResponseMessage PostSendPdf(Information info)
{
    // Your email sending mechanism, Use info object where you need, for example, info.Email
    var coverHtml = RenderRazorViewToString("~/Views/Home/Test.cshtml", null);
    var htmlContent = RenderRazorViewToString( "~/Views/Home/Test2.cshtml", null);
    string path = HttpContext.Server.MapPath("~/Content/PDF/html-string.pdf");
    PDFGenerator.CreatePdf(coverHtml, htmlContent, path);


    //PDFGenerator.CreatePdfFromURL("https://www.google.com", path);
    EmailHelper.SendMail(info.Email, "Test", "HAHA", path);


    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
    return response;
}

您可能想要创建一个 ApiController(看起来您正在从 System.Web.Mvc 实施 Controller。确保您的项目中包含 Web API。

我在示例中使用以下模型:

public class ReportModel
{
    public string ContentId { get; set; }
    public string Email { get; set; }
}

这里是 ApiController 发送 PDF 的示例:

public class SendPDFController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post([FromUri]ReportModel reportModel)
    {
        //Perform Logic
        return Request.CreateResponse(System.Net.HttpStatusCode.OK, reportModel);
    }
}

这允许您在 URI 中传递参数,在本例中为 http://localhost/api/SendPDF?contentId=123&email=someone@example.com。此格式适用于 Visual Studio 包含在 WebApiConfig:

中的默认路由
 config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

您也可以在请求的 body 中传递参数。您可以像这样更改 Post 方法:

[HttpPost]
public HttpResponseMessage Post([FromBody]ReportModel reportModel)
{
    //Perform Logic
    return Request.CreateResponse(HttpStatusCode.OK, reportModel);
}

那么您的请求 URI 将是 http://localhost/api/SendPDF、Content-Type header as application/json 和 Body:

{
    "ContentId": "124",
    "Email": "someone@example.com"
}

如果您在 body 中传递参数,JSON 请求已为您序列化到您的模型中,因此您可以从 [=24] 访问报告所需的参数=] object 在你的方法中。