2017-08-16 186 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; 
}