注入HostingEnvironment后,asp.net没有来自帖子请求的响应

时间:2015-12-11 13:06:12

标签: c# asp.net post code-injection

我只掌握ASP.net的基本知识。我一直在编写一个简单的MVP控制器,它处理JSON post请求。它工作正常,直到我尝试注入托管环境。从那时起,服务器始终使用代码500进行响应,但服务器本身没有错误。在控制器中设置断点时,似乎永远不会到达后置代码,甚至在注入后也不会调用构造函数。我不知道在哪里寻找原因。我希望有人可以帮助我。这是控制器代码:

using System;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Annotations;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.AcroForms;
using PdfSharp.Pdf.IO;
using st214.Models;
using Microsoft.AspNet.Hosting;

// For more information on enabling Web API for empty projects, visit     http://go.microsoft.com/fwlink/?LinkID=397860

namespace st214.API
{
[Route("api/[controller]")]
public class FormularController : Controller
{
    private readonly ApplicationDbContext db;
    private readonly HostingEnvironment _hostingEnvironment;

    private readonly string tempLocation;

    private Dictionary<string, string> locationsMock = new Dictionary<string, string>();

    public FormularController(ApplicationDbContext context, HostingEnvironment hostingEnvironment)
    {
        db = context;
        _hostingEnvironment = hostingEnvironment;

        tempLocation = _hostingEnvironment.WebRootPath + @"\app\formularwesen\tempForms\";

        locationsMock.Add(@"ct", @"CT_form.pdf");
        locationsMock.Add(@"uewa", @"UeWA_form.pdf");
        locationsMock.Add(@"uelab", @"UeWA_form.pdf");
        locationsMock.Add(@"uelabalt", @"UeWA_form.pdf");
    }

    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public FileStreamResult Post([FromBody] FormData formData)
    {
        var source = _hostingEnvironment.WebRootPath + @"\app\formularwesen\PDFForms\" + locationsMock[formData.name];
        var file = FillForm(source, tempLocation, formData.data, formData.print);

        FileStream pdfStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        return new FileStreamResult(pdfStream, "application/pdf")
        {
            FileDownloadName = formData.name + ".pdf"
        };
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] FormData formData)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }

    private string FillForm(string source, string destinationFolder, Dictionary<string, FormField> fields, bool print)
    {
        // Open document
        PdfDocument document = PdfReader.Open(source, PdfDocumentOpenMode.Modify);

        // set fields to be editable
        if (document.AcroForm.Elements.ContainsKey("/NeedAppearances") == false)
            document.AcroForm.Elements.Add("/NeedAppearances", new PdfSharp.Pdf.PdfBoolean(true));
        else
            document.AcroForm.Elements["/NeedAppearances"] = new PdfSharp.Pdf.PdfBoolean(true);

        // fill out fields
        foreach (KeyValuePair<string, FormField> field in fields)
        {
            // get the field
            if (field.Value.Type == "text")
            {
                PdfTextField currentField = (PdfTextField)(document.AcroForm.Fields[field.Key]);
                // create the value
                PdfString valueString = new PdfString(field.Value.Value);
                // fill the value
                try
                {
                    currentField.Value = valueString;
                }
                catch (NullReferenceException e)
                {
                    // Field not found
                }
            }

            if (field.Value.Type == "radio")
            {
                PdfCheckBoxField currentField = (PdfCheckBoxField)(document.AcroForm.Fields[field.Value.Value]);

                try
                {
                    if (currentField.HasKids)
                    {
                        foreach (var item in currentField.Fields.Elements.Items)
                        {
                            //assumes you want to "check" the checkbox.  Use "/Off" if you want to uncheck.
                            //"/Yes" is defined in your pdf document as the checked value.  May vary depending on original pdf creator.
                            ((PdfDictionary)(((PdfReference)(item)).Value)).Elements.SetName(PdfAcroField.Keys.V, "/Yes");
                            ((PdfDictionary)(((PdfReference)(item)).Value)).Elements.SetName(PdfAnnotation.Keys.AS, "/Yes");
                        }
                    }
                    else
                    {
                        currentField.Checked = true;
                    }
                }
                catch (NullReferenceException e)
                {
                    // field not found
                }
            }
        }


        // create unique file name (UUID)
        string tmpName = Guid.NewGuid().ToString() + ".pdf";

        string file = destinationFolder + tmpName;

        // if file should be printed immediately, add print function to
        // pdf document
        if(print)
            AddPrintFunction(document);

        // save the document
        document.Save(file);

        return file;
    }
    public static void AddPrintFunction(PdfDocument document)
    {
        PdfDictionary dict = new PdfDictionary(document);

        // According to the PDF Reference the dictionary requires two elements.
        // A key /S that specifies the action name, and a key /JS that set the JavaScript to run.
        dict.Elements["/S"] = new PdfName("/JavaScript");
        dict.Elements["/JS"] = new PdfName("/this.print(true);");

        document.Internals.AddObject(dict);
        document.Internals.Catalog.Elements["/OpenAction"] = PdfInternals.GetReference(dict);
    }

    private string getTemplateFile(string templateName)
    {
        FormLocation template = db.FormLocations.Where(f => f.name == templateName).First();
        return template.file;
    }
}
}

1 个答案:

答案 0 :(得分:0)

好的,我自己发现了。您需要注入IHostingEnvironment,而不是HostingEnvironment才能使其正常工作。我没有足够的经验来解释每一个是什么,也许有人可以在评论中澄清它,只是想在我发现问题时回答这个问题。