C#使用POST方法

时间:2017-08-16 03:15:25

标签: c# entity-framework asp.net-web-api html-to-pdf nreco

我这里有一个代码,它实际上将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();
}

我想使用POST将其转换为api格式(api / SendPDF),其中包含将发送给它的内容ID和电子邮件地址,但我不知道该怎么做,因为我对MVC很新, Web API。感谢一些帮助。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

您可能想要创建ApiController(看起来您正在Controller实施System.Web.Mvc。请确保在项目中包含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=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对象访问报告所需的参数。