我正在尝试将字符串从客户端传输到 ASP.NET MVC4 应用程序。
但是我收不到字符串,要么是null,要么找不到post方法(404错误)
传输字符串的客户端代码(控制台应用程序):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:49032/api/test");
request.Credentials = new NetworkCredential("user", "pw");
request.Method = "POST";
string postData = "Short test...";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
ASP.NET Web Api 控制器:
public class TestController : ApiController
{
[Authorize]
public String Post(byte[] value)
{
return value.Length.ToString();
}
}
在这种情况下,我可以调用“Post”方法,但“值”是
NULL
。
如果我将方法签名更改为(字符串值),那么它永远不会被调用。
即使“没有”[授权]设置,它也有同样奇怪的行为。 -> 所以这与用户身份验证无关。
你知道我做错了什么吗? 我很感激任何帮助。
您似乎在 Web API 控制器操作上使用了一些
[Authorize]
属性,我不明白这与您的问题有什么关系。
那么,让我们开始实践吧。下面是一个简单的 Web API 控制器的样子:
public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}
以及就此而言的消费者:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}
[FromBody]
装饰以及客户端 POST 数据的 =
前缀。我建议您阅读Web API 如何进行参数绑定,以更好地理解这些概念。
就
[Authorize]
属性而言,这可用于保护服务器上的某些操作仅可由经过身份验证的用户访问。实际上,您在这里想要实现的目标还不清楚。顺便说一句,您应该在问题中更清楚地说明这一点。您是否正在尝试了解参数绑定在 ASP.NET Web API 中的工作原理(如果这是您的目标,请阅读我链接到的文章)或尝试进行一些身份验证和/或授权?如果您是第二种情况,您可能会发现我就该主题撰写的 following post
很有趣,可以帮助您入门。
如果在阅读了我链接到的材料后,您像我一样对自己说,WTF,我所需要做的就是将字符串 POST 到服务器端端点,而我需要执行所有这些操作?决不。然后检查ServiceStack。您将为与 Web API 进行比较奠定良好的基础。我不知道微软的人在设计 Web API 时在想什么,但是说真的,我们应该为 HTML(想想 Razor)和 REST 东西有单独的基本控制器?这不可能是严重的。
如果您接受使用 HTTP 的事实,Web API 会非常有效。当您开始尝试假装通过线路发送对象时,事情就开始变得混乱了。
public class TextController : ApiController
{
public HttpResponseMessage Post(HttpRequestMessage request) {
var someText = request.Content.ReadAsStringAsync().Result;
return new HttpResponseMessage() {Content = new StringContent(someText)};
}
}
该控制器将处理 HTTP 请求,从有效负载中读取字符串并返回该字符串。
您可以使用 HttpClient 通过传递 StringContent 实例来调用它。 StringContent 将默认使用 text/plain 作为媒体类型。这正是您想要通过的。
[Fact]
public void PostAString()
{
var client = new HttpClient();
var content = new StringContent("Some text");
var response = client.PostAsync("http://oak:9999/api/text", content).Result;
Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);
}
对于 WebAPI,这里是检索正文文本的代码,无需通过其特殊的 [FromBody] 绑定。
public class YourController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
string bodyText = this.Request.Content.ReadAsStringAsync().Result;
//more code here...
}
}
我使用此代码来发布 HttpRequests。
/// <summary>
/// Post this message.
/// </summary>
/// <param name="url">URL of the document.</param>
/// <param name="bytes">The bytes.</param>
public T Post<T>(string url, byte[] bytes)
{
T item;
var request = WritePost(url, bytes);
using (var response = request.GetResponse() as HttpWebResponse)
{
item = DeserializeResponse<T>(response);
response.Close();
}
return item;
}
/// <summary>
/// Writes the post.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="bytes">The bytes.</param>
/// <returns></returns>
private static HttpWebRequest WritePost(string url, byte[] bytes)
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
Stream stream = null;
try
{
request.Headers.Clear();
request.PreAuthenticate = true;
request.Connection = null;
request.Expect = null;
request.KeepAlive = false;
request.ContentLength = bytes.Length;
request.Timeout = -1;
request.Method = "POST";
stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
GetErrorResponse(url, e);
}
finally
{
if (stream != null)
{
stream.Flush();
stream.Close();
}
}
return request;
}
关于您的代码,请在没有内容的情况下尝试。输入(
request.ContentType = "application/x-www-form-urlencoded";
)
更新
我认为问题在于您如何尝试检索该值。当您执行 POST 并通过 Stream 发送字节时,它们不会作为参数传递到操作中。您需要通过服务器上的流检索字节。
在服务器上,尝试从流中获取字节。以下代码是我使用的。
/// <summary> Gets the body. </summary>
/// <returns> The body. </returns>
protected byte[] GetBytes()
{
byte[] bytes;
using (var binaryReader = new BinaryReader(Request.InputStream))
{
bytes = binaryReader.ReadBytes(Request.ContentLength);
}
return bytes;
}
Darrel 的回答当然是正确的。需要补充的一件事是尝试绑定到包含单个标记(如“hello”)的主体的原因。
它不完全是 URL 形式的编码数据。在前面添加“=”,如下所示:
=hello
它成为单个键值对的 URL 形式编码,名称为空,值为“hello”。
但是,更好的解决方案是在上传字符串时使用 application/json :
POST /api/sample HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: host:8080
Content-Length: 7
"Hello"
使用 HttpClient 您可以执行以下操作:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
亨里克
我遇到这个问题,找到这篇文章。 http://www.jasonwatmore.com/post/2014/04/18/Post-a-simple-string-value-from-AngularJS-to-NET-Web-API.aspx
我找到的解决方案是简单地将字符串值包装在 double 中 在你的 js 帖子中引用
就像一个魅力!仅供参考
([FromBody] IDictionary<string,object> data)