400 bad request from web api 2

时间:2016-04-04 17:34:53

标签: asp.net-mvc asp.net-web-api asp.net-web-api2

I have a simple web api 2 controller returning an object in JSON format, when i try to call it using an httpclient i get a bad request,but when directly pasting the url in the browser i get the correct result:

http://ipaddress/api/cov/GetViders/latitude/longitude/ works well.

http://ipaddress/GetViders/latitude/longitude/ 400 bad request.

Api controller:

[Route("api/cov/GetViders/{latitude}/{longitude}/")]
    public IHttpActionResult GetViders(float latitude, float longitude)
    {

      var vm = ....


        return Json(vm);
    }

.net client : (web controller)

[Route("GetViders/{latitude}/{longitude}")]
    public async Task<IEnumerable<ViderListViewModel>> GetViders(float latitude, float longitude)
    {
        using (var client = new HttpClient())
        {
            // TODO - Send HTTP requests
            client.BaseAddress = new Uri("http://...../");

            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
            client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");
            client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");

            HttpResponseMessage response = await client.GetAsync("api/cov/GetViders/" + latitude + "/" + longitude + "/");

            if (response.IsSuccessStatusCode)
            {
                List<ViderListViewModel> viders = await response.Content.ReadAsAsync<List<ViderListViewModel>>();
                return viders;
            }
            return null;
        }
    }

Edit:

I also tried to call the api using a webclient :

using (var client = new WebClient())
        {
            var json = client.DownloadString(url);
            var serializer = new JavaScriptSerializer();
            IEnumerable<ViderListViewModel> model = serializer.Deserialize<IEnumerable<ViderListViewModel>>(json);

        }

I got the same error : 400 bad request.

P.S.:

Even if the api and the client are two different projects, they are both located on the same server, so CORS should not be the cause of the issue, that said i have added that to make sure it's not the cause:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

any idea what i'm doing wrong ?

0 个答案:

没有答案