我有一个调用应用程序,该应用程序具有如下代码(我无法更改此应用程序)
try
{
string request = string.Format("UniqueId={0}&MobileNumber={1}&UssdText={2}&Type={3}&AccountId={4}", "1", "2", "3", "4",
"5");
using (HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())))
{
string url = "http://localhost/MocExternalEntityApis/MyUssd/Getdata3";
client.DefaultRequestHeaders.ExpectContinue = false;
StringContent content = new StringContent(request);
content.Headers.Clear();
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(url, content).ConfigureAwait(false);
var readAsString = await response.Content.ReadAsStringAsync();
client.Dispose();
}
}
catch (Exception ex)
{
}
我的Web API控制器中总是有空对象
[HttpPost]
[ActionName("GetData3")]
public JsonResult<MyResponse> GetData3(MyInput obj)
{
if (obj != null)
{
Logger.DebugFormat("UniqueId:{0}, MobileNumber:{1}, UssdText:{2}, Type:{3}, AccountId:{4}",
obj.UniqueId, obj.MobileNumber, obj.UssdText, obj.Type, obj.AccountId);
if (obj.Type == "3")
{
Task.Factory.StartNew(async () =>
{
await ProcessCallbackHandlingofPinRespone(obj.UniqueId, obj.MobileNumber,
obj.UssdText);
});
}
else
{
Task.Factory.StartNew(async () =>
{
await ProcessCallbackHandlingOfNotification(obj.UniqueId, obj.MobileNumber,
obj.UssdText);
});
}
}
else
{
Logger.DebugFormat("Empty Object");
}
return Json(new MyResponse { Status = "OK" });
}
[Serializable]
public class MyInput
{
[JsonProperty(PropertyName = "UniqueId")]
public string UniqueId { get; set; }
[JsonProperty(PropertyName = "MobileNumber")]
public string MobileNumber { get; set; }
[JsonProperty(PropertyName = "UssdText")]
public string UssdText { get; set; }
[JsonProperty(PropertyName = "Type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "AccountId")]
public string AccountId { get; set; }
}
我需要在我的Web Api中进行哪些更改才能使用数据。
调用我的api的日志就像 请求:
Method: POST, RequestUri: 'http://localhost/MocExternalEntityApis/MyUssd/Getdata3', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: application/json
}
UniqueId=1&MobileNumber=2&UssdText=3&Type=4&AccountId=5
答案 0 :(得分:0)
尝试将[FromBody]属性添加到控制器操作中,使其看起来像这样:
[ActionName("GetData3")]
public JsonResult<MyResponse> GetData3([FromBody]MyInput obj)
{
...
}
诸如int之类的简单类型会自动绑定,但对于MyInput
之类的更复杂类型,Web api会尝试使用媒体类型格式化程序从消息正文中读取值。通过提供[FromBody]属性,它将强制将请求正文读取为简单类型,并应按您的期望对其进行序列化
答案 1 :(得分:0)
我最终能够通过Request.Content获取提交的内容
我在上面的评论中提到的示例代码是
public class ValuesController : ApiController {
// POST api/values
[HttpPost]
public async Task Post() {
var requestContent = Request.Content;
var jsonContent = await requestContent.ReadAsStringAsync();
}
}