2017-08-16 26 views
-1

我这里有一个代码,这实际上转换HTML到PDF,并将其发送到电子邮件,但它是在的ActionResult:C#更改的ActionResult到IHttpActionResult使用POST方法

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("[email protected]", "Test", "HAHA", path); 

    return View(); 
} 

我想变成一个API格式(api/SendPDF)使用POST与它将被发送到的内容ID和电子邮件地址,但我不知道该怎么做,因为我对MVC和Web API非常陌生。在这方面感谢一些帮助。

回答

1

你可能会想创建一个ApiController(它看起来像您正在实现从System.Web.MvcController。请确保您在项目中包含的Web API。

我用下面的模型在我的例子:

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

这里是发送您的PDF的例子ApiController

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 protected]。这种格式将与缺省路由的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": "[email protected]" 
} 

如果你在身体通过您的参数, JSON请求已经序列化到您的模型中,因此您可以从方法中的reportModel对象访问您需要的报告参数。

1

首先创建一个类,例如。 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; 
}