【问题标题】:Not able to fill data into web api controller无法将数据填充到 Web api 控制器中
【发布时间】:2018-09-19 11:22:03
【问题描述】:

我有一个调用应用程序,其代码如下(我无法更改此应用程序)

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; }
}

我需要在 My 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

【问题讨论】:

标签: c# asp.net-web-api .net-4.5


【解决方案1】:

尝试将 [FromBody] 属性添加到您的控制器操作中,使其看起来像这样:

[ActionName("GetData3")]
public JsonResult<MyResponse> GetData3([FromBody]MyInput obj)
{
  ...
}

简单类型(例如 int)会自动绑定,但对于更复杂的类型(例如 MyInput),Web api 会尝试使用媒体类型格式化程序从消息正文中读取值。通过提供 [FromBody] 属性,它将强制将请求正文作为简单类型读取,并应按您的预期对其进行序列化

更多信息可以在这里找到:https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

【讨论】:

  • 已经做到了。根据我在帖子中添加的评论,我找到了解决方案
【解决方案2】:

我最终能够通过 Request.Content 获得提交的内容

我在上面评论中提到的示例代码是

public class ValuesController : ApiController {
    // POST api/values
    [HttpPost]
    public async Task Post() {
        var requestContent = Request.Content;
        var jsonContent = await requestContent.ReadAsStringAsync();

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2018-06-07
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多