将字符串从Angular传递到API [英] Passing string from Angular to API
本文介绍了将字符串从Angular传递到API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过Angular在我的ASP.NET Core MVC API控制器中填充一个字符串参数.
I want to fill in one string parameter in my ASP.NET Core MVC API controller via Angular.
我有这个工作电话:
API
//A class to wrap my string
public class Foo
{
public string bar { get; set; }
}
[HttpPost]
public JsonResult GetDetails([FromBody] Foo bar) { ... }
角度(服务)
public get() {
let bar: any = new Object();
bar.foo = 'Hello World';
return this._httpClient.post('api/GetDetails', bar).toPromise();
}
但是我真正想要的是传递一个字符串,而不必将其包装在这样的类中:
But what I really want is pass a string without having to wrap it in a class like this:
API
[HttpPost]
public JsonResult GetDetails([FromBody] string bar) { ... }
角度(服务)
public get() {
let bar: string = "Hello World";
return this._httpClient.post('api/GetDetails', bar).toPromise();
}
但是我收到错误消息,例如它是不受支持的媒体类型,或者'bar'保持为空.
仅传递一个值的正确语法是什么?
另一件事是,我可以将Angular的整数传递给API,但不能传递字符串.
But I get errors like it's an Unsupported Media Type or 'bar' stays null.
What is the right syntax to just pass one value?
The other thing is, I can pass an integer from Angular to the API just fine but not a string.
推荐答案
尝试一下:
let bar = JSON.stringify({'foo' : 'Hello World'});
let body = new HttpParams();
body = body.set('bar', bar);
http.post('/api/GetDetails', body).subscribe();
这篇关于将字符串从Angular传递到API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文