使用参数

时间:2018-03-13 20:06:43

标签: c# asp.net asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我正在学习网络API,正在努力 - 我遇到了麻烦。我可以发布它很好并在api上的方法中没有参数时得到响应,例如这可行...

客户端

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + T.Access_Token);
    var req = new HttpRequestMessage(HttpMethod.Post, "https://baseurl/api/controller/sites");
    var response = await client.SendAsync(req);

    if (response.IsSuccessStatusCode)
    {
         string result = await response.Content.ReadAsStringAsync();

         List<Site_2016> sites = Library.Data.Json.FromJson<List<Site_2016>>(result);

         return sites;
    }
    else return new List<Site_2016>();
}

阿比

    [HttpPost]
    [Route("sites")]
    public async Task<IHttpActionResult> GetSites()
    {

        //Do stuff
        return Ok(Sites);

    }

但是当我通过一些像这样的参数时,我无法为我的生活做好准备......

客户端

using (var client = new HttpClient())
{
        Dictionary<String, String> dict = new Dictionary<string, string>();
        dict.Add("identifier", instance);
        dict.Add("endOfDay", IsEndOfDayOnly.ToString());

        var content = new FormUrlEncodedContent(dict);
        client.BaseAddress = new Uri("https://baseurl/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + T.Access_Token);

        var response = await client.PostAsync("api/controller/lastsaledate", content);

        if (response.IsSuccessStatusCode)
        {
            string result = await response.Content.ReadAsStringAsync();

            KeyValuePair<String, DateTime> LastPush = Library.Data.Json.FromJson<KeyValuePair<String, DateTime>>(result);

            return LastPush;
        }
        else
        {
            return new KeyValuePair<string, DateTime>();
        }
    }

阿比

    [HttpPost]
    [Route("lastsaledate")]
    public async Task<IHttpActionResult> GetLastSalesUpdate(string identifier, bool endOfDay)
    {
        //do stuff
        return Ok(Result);
    }

响应返回404,如果可能是路由问题,我正在徘徊?持票人令牌对两个帖子都有效,如果我禁用授权,那么我得到相同的结果。 api / controller / action url绝对正确。

1 个答案:

答案 0 :(得分:1)

是的,在这种情况下,你可以试试这个

var response = await client.PostAsync(string.format("api/controller/lastsaledate?identifier={0}&endOfDay{1}",instance,IsEndOfDayOnly), content);

删除 dict

或者你可以试试这个

[HttpPost]
    [Route("lastsaledate")]
    public async Task<IHttpActionResult> GetLastSalesUpdate([FromBody]string identifier, [FromBody]bool endOfDay)
    {
        //do stuff
        return Ok(Result);
    }

或者你可以试试这个

[HttpPost]
        [Route("lastsaledate")]
        public async Task<IHttpActionResult> GetLastSalesUpdate(testClass myParam)
        {
            //do stuff
            return Ok(Result);
        }

public class testClass
{
   public string identifier;
   public bool endOfDay;
}