我正在用C# .Net4.8编写客户端和API。我是来自客户端的POSTing数据,并且在端点方法上有一个ActionFilterAttribute
。我想在POSTed方法中读取ActionFilterAttribute
数据。我发现我能够使用FormUrlEncodedContent
发布表单数据,并且它是被接收的,但是当我尝试使用POSTing JSON数据时,它是不被接收的。
如何更改客户端代码或API代码以正确发布JSON?
POSTing表单数据是这样工作的:
HttpClientHandler handler = new HttpClientHandler()
HttpClient httpClient = new HttpClient(handler);
FormUrlEncodedContent formString = new FormUrlEncodedContent(data);
response = httpClient.PostAsync(url, formString).Result; // run synchronously
然后在API端,填充dataFromClient
:
public class myFilter : ActionFilterAttribute
{
public string Feature { get; set; }
public myFilter(string feature)
{
this.Feature = feature;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string dataFromClient = (HttpContext.Current.Request.Params["dataFromClient"] == null) ? "" : HttpContext.Current.Request.Params["dataFromClient"];
// do other stuff with dataFromClient here
}
}
像这样的POSTing JSON数据不起作用:
HttpClientHandler handler = new HttpClientHandler()
HttpClient httpClient = new HttpClient(handler);
StringContent stringContent = new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json");
response = httpClient.PostAsync(url, stringContent).Result; // run synchronously
使用此方法,API中的dataFromClient
为空。
发布于 2021-11-18 15:54:36
由于您正在发布application/json
,所以您应该阅读请求正文。我想,这是你想要的;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var initialBody = request.Body;
try
{
request.EnableRewind();
using (StreamReader reader = new StreamReader(request.Body))
{
string dataFromClient = reader.ReadToEnd();
// do other stuff with dataFromClient here
return dataFromClient;
}
}
finally
{
request.Body = initialBody;
}
filterContext.Request.Body.Position = 0
return string.Empty;
}
https://stackoverflow.com/questions/70015542
复制相似问题