Angular HttpClient post 无法发送简单的字符串参数
Angular HttpClient post cannot send simple string parameter
我想向以字符串作为参数的 C# 服务发送请求。我写了一个这样的 angular 服务:
export class CategoryService {
constructor(private http: HttpClient) { }
getCategory(categoryName: string): Observable<Category> {
console.log(categoryName);
return this.http.post("/category/GetCategory", { categoryName: categoryName }, { headers: new HttpHeaders({ 'Content-type': 'application/json' }) });
}
我也试过:
export class CategoryService {
constructor(private http: HttpClient) { }
getCategory(categoryName: string): Observable<Category> {
console.log(categoryName);
return this.http.post("/category/GetCategory", categoryName , { headers: new HttpHeaders({ 'Content-type': 'application/json' }) });
}
但是当他们都成功发送请求时,参数始终为null。
我的 C# 服务是:
[HttpPost]
public IActionResult GetCategory([FromBody]string categoryName)
我在这里找到了解决方案:
我还应该从我的服务参数中删除 [FromBody]。
我可以提供我自己的解决方案:)
Angular:
Func(data: string): Observable<any> {
let params = new HttpParams();
params = params.set('data', data);
return this.http.post("url", params);
}
C#:
public IActionResult Method([FromForm]string data)
Best and easiest solution
this.http.post(this.serverAddress + API_ADDRESS + '?param=' + yourStringParam, null);
正如@Niladri 所说,这对我有用:
... using JSON.stringify(categoryName) in your typescript service with FromBody in controller
这也很重要:
... keep the content-type as HttpHeaders({ 'Content-Type': 'application/json' })
它与控制器方法中的 FromBody 一起工作:)
我想向以字符串作为参数的 C# 服务发送请求。我写了一个这样的 angular 服务:
export class CategoryService {
constructor(private http: HttpClient) { }
getCategory(categoryName: string): Observable<Category> {
console.log(categoryName);
return this.http.post("/category/GetCategory", { categoryName: categoryName }, { headers: new HttpHeaders({ 'Content-type': 'application/json' }) });
}
我也试过:
export class CategoryService {
constructor(private http: HttpClient) { }
getCategory(categoryName: string): Observable<Category> {
console.log(categoryName);
return this.http.post("/category/GetCategory", categoryName , { headers: new HttpHeaders({ 'Content-type': 'application/json' }) });
}
但是当他们都成功发送请求时,参数始终为null。 我的 C# 服务是:
[HttpPost]
public IActionResult GetCategory([FromBody]string categoryName)
我在这里找到了解决方案:
我可以提供我自己的解决方案:)
Angular:
Func(data: string): Observable<any> {
let params = new HttpParams();
params = params.set('data', data);
return this.http.post("url", params);
}
C#:
public IActionResult Method([FromForm]string data)
Best and easiest solution
this.http.post(this.serverAddress + API_ADDRESS + '?param=' + yourStringParam, null);
正如@Niladri 所说,这对我有用:
... using JSON.stringify(categoryName) in your typescript service with FromBody in controller
这也很重要:
... keep the content-type as HttpHeaders({ 'Content-Type': 'application/json' })
它与控制器方法中的 FromBody 一起工作:)