Http Post不执行到ASP.. NET,但是GET请求可以
本文关键字:GET 但是 请求 NET Post 执行 ASP Http | 更新日期: 2023-09-27 18:04:50
我正在尝试在Angular2中发出post请求。由于某种原因,我不能发出POST请求。我将客户端和服务器都更改为GET请求,并保留其他所有内容相同,并且它工作得很好。所以我想知道我是否可以配置头部不同的方式,以便能够使POST请求。
更新
所以我设法让它执行,但现在位置参数显示为空
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')
);
}
服务器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);
}
}
}
错误位置(null)
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)
编辑:
最好在服务器中创建一个class
:
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
并将方法签名更改为:
public async Task<IActionResult> CurrentForecasts(Location location)
从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)
HttpGet
不应该处理您的post请求。你可能需要在你的Web API控制器上定义一个RouteAttribute
。
[HttpPost]
[Route("api/SampleData")]
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("Failed");
同样,在客户端你也可以说:
let headers = new Headers();
headers.append('Content-Type', 'application/json')
let body = latitude+','+longitude ;
this.http.post('/api/SampleData/',body, { headers: headers })
.map(response => response.json())
.subscribe(
data => this.Debug(data),
err => console.log("Error: 'n"+err),
() => console.log('Get Complete')
);
返回Json(null)
或Json("Failed")
可能会导致上述错误。可能如果你试图把你的响应包装成一些对象,有一些Success
属性是布尔,这样你就可以在尝试读取一些data
属性之前先在你的一边查询它。如果您创建一个模型或视图模型,如:
public class ResponseModel
{
public IList<SomeModel> Data {get; set;}
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
然后围绕上述模型创建您的响应。您可能希望/需要对上述模型进行详细说明。
. net中的默认路由是将操作映射到相似的方法名(按约定编码)。如果没有直接匹配的方法,默认GET操作将查找第一个可用的方法。
因为你的控制器名为"SampleData",你需要…
A)用类似的方式重命名你的方法,如"GetSampleData","PostSampleData"等 B)为HttpPost和Action添加数据注释,以便路由器知道如何映射诸如 之类的东西[HttpPost]
[ActionName("CurrentForecasts")]
public async Task<IActionResult> CurrentForecasts(string location)
{
...your code here
}
只要更新你的主体,使表单字段匹配,你应该设置。
注意:下面的代码是AngularJS的解决方案。对于Angular2,可以看看这个。
var param = {location: body}
var configObj = { headers: headers, params: param };
this.http.post('/api/SampleData/CurrentForecasts', null, configObj )