c# - ASP.NET POST 接收问题
问题描述
我在控制器中有以下方法Api
[HttpPost]
public string TestMethod()
{
var nvc = Request.Form;
return Request.HttpMethod + " | " + string.Join("&", nvc.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(nvc[a])));
}
当我从浏览器发出 POST 请求时,它可以正常工作,但如果我尝试使用 C# 发送 POST,ASP 会返回 404 错误如果我[HttpPost]
在该方法之前删除,ASP 会告诉我正在尝试发出 GET 请求。
string url = "https://localhost:44300/Api/TestMethod";
Dictionary<string, string> pars = new Dictionary<string, string>();
pars.Add("a", "b");
pars.Add("c", "d");
pars.Add("e", "f");
Console.WriteLine(POST(url, pars));
我试过用标题来操作,但没用。这是我的 POST 方法
static string POST(string url, Dictionary<string, string> parameters)
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(new Uri(url));
hwr.KeepAlive = false;
hwr.Method = "POST";
hwr.ContentType = "application/x-www-form-urlencoded";
hwr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0";
byte[] data = Encoding.UTF8.GetBytes(MakeQueryString(parameters));
hwr.ContentLength = data.Length;
using (Stream reqStream = hwr.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
string result;
using (HttpWebResponse response = (HttpWebResponse)hwr.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
result = sr.ReadToEnd();
}
}
return result;
}
UPD 1:我使用 RESTClient for Firefox 发送 POST 请求;UPD 2:我的 C# 方法适用于其他网站
解决方案
我找到了解决方案。有个问题在web.config
<sessionState timeout="90" cookieless="AutoDetect" />
AutoDetect
是否有问题,要解决它,需要删除cookieless="AutoDetect"
推荐阅读
- java - 无法将 XSD 转换为 Java 类
- javascript - 如何让jsdom等待html页面的完整呈现..?
- sql - IN 条件左侧的多列
- javascript - JS 在“return array('html' => $response);”中不起作用
- visual-studio-code - 什么是 Visual Studio 代码(VSCode)ftp-simple 中的“找不到命令 'ftp-config'”错误
- c++ - 如何实现具有自然语法的线程安全容器?
- angular - 如何在 *ngFor 中使用 API 调用
- ios - 如何处理订阅收据中缺少“latest_receipt_info”?
- android - 在主要内容后面发送抽屉内容以显示效果
- php - 如何使用codeigniter视图在jasper报告中传递参数