一键将相同的 XML 文件序列化并显示到 Web 浏览器

Serializing and displaying same XML file to the web browser in one button

正如主题所说,我想序列化一个对象并在网络浏览器上显示它。 当尝试这样做时,我得到一个错误 "IOException was unhandled by user code"。该进程无法访问 >... 本地地图。

所以我注意到在序列化过程中,不太可能同时写入同一个文件。然而。是否有可能首先将其序列化。然后打开? 或者有更好的解决方案吗?

public ActionResult Serializing(Models.SerializerModel model)
{
    var username = model.Username.ToString();
    if (ModelState.IsValid)
    {
        string path = Server.MapPath("~/xml");

        XmlSerializer serial = new XmlSerializer(model.GetType());
        System.IO.StreamWriter writer = new System.IO.StreamWriter(path + "\"+ username + ".xml");
        serial.Serialize(writer, model);
        //This code below i want to execute after the above one is done
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/xml";
        //During WriteFile i get the error IO
        Response.WriteFile(Server.MapPath("~/xml\hello.xml"));
        Response.Flush();
        Response.End();
        return RedirectToAction("Index", "Profile");

    }
    return RedirectToAction("Index", "Profile");
}

如果我将响应代码和序列化代码分成 2 个不同的按钮,代码就可以工作,但这不是我想要实现的。

您得到 IOException 是因为您的写入流在您开始读取它以推送它作为响应时仍然打开。我对您的代码进行了一些更改。这应该可以解决您的问题。另外我不确定你是否真的需要 Response.End() call

public ActionResult Serializing(Models.SerializerModel model)
{
    var username = model.Username.ToString();
    if (ModelState.IsValid)
    {
        string path = Server.MapPath("~/xml");
        //First write to file. using statement will take care of closing writer stream. 
        XmlSerializer serial = new XmlSerializer(model.GetType());
        using (var writer = new System.IO.StreamWriter(path + "\" + username + ".xml"))
        {
            serial.Serialize(writer, model);
            writer.Flush();
        }

        //This code below i want to execute after the above one is done
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/xml";
        //During WriteFile i get the error IO
        Response.WriteFile(Server.MapPath("~/xml/hello.xml"));
        Response.Flush();
        //Response.End();   I am not sure if this statement is really needed here.
        return RedirectToAction("Index", "Profile");

    }
    return RedirectToAction("Index", "Profile");
}