-1

I have a code here which actually converts HTML to PDF and sends it to an email but it is in 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();
}

I want to turn this into a api format (api/SendPDF) using POST with the content ID and email address which it will be sent to, but I am not sure how to do it since I am very new to MVC and Web API. Appreciate some help on this.

4

2 回答 2

1

您可能想要创建一个ApiController(看起来您是ControllerSystem.Web.Mvc.

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

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 }
);

您还可以在请求正文中传递参数。你会Post像这样改变你的方法:

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

那么您的请求 URI 将是http://localhost/api/SendPDF,Content-Type 标头为application/json,和正文:

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

如果您在正文中传递参数,则 JSON 请求已为您序列化到您的模型中,因此您可以从reportModel方法中的对象访问报告所需的参数。

于 2017-08-16T07:27:12.053 回答
1

首先创建一个类,例如。信息.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;
}
于 2017-08-16T05:16:38.470 回答