John John - 3 months ago 27
C# Question

Angular2 - http Post not executing to ASP.NET. GET executs

I'm trying to make a post request in Angular2. For some reason I cant make POST request. I changed both the client and server to GET request and left everything else the same, and it works fine. So im wondering if i can to configure the header a different way to be able to make the POST request.

Update

So i managed to get it to execute, but now the location parameter is showing null

Client

search(latitude: any, longitude: any){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = JSON.stringify({ latitude, longitude });
this.http.post('/api/SampleData/CurrentForecasts',body, { headers: headers })
.map(response => response.json())
.subscribe(
data => this.Debug(data),
err => console.log("Error: \n"+err),
() => console.log('Get Complete')
);
}


Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Weather.Controllers
{
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpPost("[action]")]
public async Task<IActionResult> CurrentForecasts(string location)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(" https://api.forecast.io/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

// HTTP GET
HttpResponseMessage response = await client.GetAsync("forecast/APIKEY/"+location);
if (response.IsSuccessStatusCode)
{
var forecast = await response.Content.ReadAsStringAsync();
return Content(forecast, "application/json");
}
}
return Json(null);
}
[HttpGet("[action]")]
public async Task<IActionResult> SendRequest()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(" https://api.forecast.io/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

// HTTP GET
HttpResponseMessage response = await client.GetAsync("forecast/APIKEY/37.8267,-122.423");
if (response.IsSuccessStatusCode)
{
var forecast = await response.Content.ReadAsStringAsync();
return Content(forecast, "application/json");
}
}
return Json(null);
}
}
}


Error
location [null]

Answer
import {Http, Response, Headers, RequestOptions, URLSearchParams} from 'angular2/http';


let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
   headers: headers,           
   search: new URLSearchParams('location='+body)
});
this.http.post('/api/SampleData/CurrentForecasts', null, options)

Edit: It would be better idea to create a class in your server:

public class Location
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

And change your method signiture to:

public async Task<IActionResult> CurrentForecasts(Location location)

To post data from Angular2:

let location = { Latitude: latitude, Longitude: longitude }
let headers = new Headers({ 'Content-Type': 'application/json' });
let body = JSON.stringify(location);
this.http.post('/api/SampleData/CurrentForecasts', body, headers)
Comments