gpt4 book ai didi

c# - 手动发布到 Asp.Net MVC Controller

转载 作者:太空狗 更新时间:2023-10-30 01:25:43 26 4
gpt4 key购买 nike

我有一个看起来像这样的 Controller ,用于将 xml 导入我的站点:

    [HttpPost]
public ActionResult Import(string xml)
{

我有一个独立的应用程序,它读取一个 xml 文件并将其发送到 url。它看起来像这样:

    static void Main(string[] args)
{
var reader = new StreamReader(@"myfile.xml");
var request = WebRequest.Create("http://localhost:41379/mycontroller/import");
request.Method = "POST";
request.ContentType = "text/xml";
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(reader.ReadToEnd());
sw.Close();
var theResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(theResponse.GetResponseStream());
var response = sr.ReadToEnd();
}

Controller 被正确调用,但当我进入那里时,参数为空。我很确定我只是没有设置正确的内容类型或类似的东西。对 xml 进行编码以便框架能够获取它并将其正确地提供给 Controller 的正确方法是什么?

最佳答案

使用 WebClient.UploadFile 为自己省去很多痛苦.

我把你带错了路,我写了一个看起来工作正常的 Controller 和客户端:

Controller

public class HomeController : Controller
{
public ActionResult Upload()
{
XDocument doc;
using (var sr = new StreamReader(Request.InputStream))
{
doc = XDocument.Load(sr);
}
return Content(doc.ToString());
}
}

客户端

static void Main(string[] args)
{

var req = (HttpWebRequest)WebRequest.Create("http://host/Home/Upload");
req.Method = "POST";
req.ContentType = "text/xml";

using (var stream = File.OpenRead("myfile.xml"))
using (var requestStream = req.GetRequestStream()) {
stream.CopyTo(requestStream);
}


using (var response = (HttpWebResponse) req.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
XDocument doc = XDocument.Load(sr);
Console.WriteLine(doc);
}


Console.ReadKey();
}

关于c# - 手动发布到 Asp.Net MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6379329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com