Angular2 HTTP Post ASP.NET MVC Web API

2019-01-15 08:07发布

How do you properly create a Web API POST of complex object or multiple parameters using Angular2?

I have a service component in Angular2 as seen below:

public signin(inputEmail: string, inputPassword: string): Observable<Response> {
    return this.http.post('/api/account/signin', JSON.stringify({ Email: inputEmail, Password: inputPassword}), this.options);
}

The targeted web api is seen below:

[HttpPost]
[Route("signin")]
public async Task<IActionResult> Signin(string email, string password)
{
       ....
}

This does not work because I need to convert the parameters of the web api into a single POCO class entity with Email and Password properties and put the [FromBody] attribute: Signin([FromBody] Credential credential)

Without using [FromURI] (POST requests with query strings?), how can I make POSTs of multiple parameters or complex objects without converting these parameters into a single POCO class?

Because what if I have numerous Web API POST actions with parameters like (string sensitiveInfo1, string name, int sensitiveInfo2) or (ClassifiedInfo info, string sensitiveInfo1, string sensitiveInfo2), do I need to convert them all to POCO classes and always use [FromBody]?

PS. I was using RestangularJS before and it can posts anything (mulitple primitive objects and complex objects) without my Web API actions having [FromBody] attributes. Will about to investigate how RestangularJS do it.

7条回答
Anthone
2楼-- · 2019-01-15 08:13

Try this, passing a complex class object into a single data parameter.

var SearchQuery = function () {
    this.Alphabet = null;
    this.Search = false;
    this.Keyword = null;
    this.RegionList = null;
};
var para = new SearchQuery();
{ data: JSON.stringify(para) } - Post Data

you can receive it using a JObject in your API controller and deserialize it as according to your classes.

查看更多
Ridiculous、
3楼-- · 2019-01-15 08:18

WebAPI does not provide this out of the box. If you try to get understanding of web API bindings, you might be able to figure out why.

I think this article might help.

The generic rules are:

– simple, string-convertible parameters (value types, strings, Guids, DateTimes and so on) are by default read from URI

– complex types are by default read from the body

– collections of simple parameters are by default read from the body too

– you cannot compose a single model based on input from both URI and request body, it has to be one or the other

查看更多
别忘想泡老子
4楼-- · 2019-01-15 08:22

WebApi will be able to deserialize your Credential object provided the JSON object has the same field names (I am not sure about case so you may be right here). You seem to be missing the headers from the post call in your Angular2 component.

Can you check the Content-Type using Chrome Debugger or Fiddler? It should be application/json.

查看更多
仙女界的扛把子
5楼-- · 2019-01-15 08:23

Perhaps you should post with options:

{ 
   headers: new Headers({
   'Content-Type': 'application/x-www-form-urlencoded'
   })
}

and encode data like

jQuery.param({user:'bla', password: 'bla'});
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-15 08:25

If you call Web API 2.2 post method from Angular 2 type script, dont forget to add following header content and parameter object.

let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
 var params = new URLSearchParams();
        params.set('userid', '102');
        params.set('username', 'foo');

 return this._http.post('http://localhost:6579/api/PostUser', params.toString(), { headers: headers }).map(res => res.json());
查看更多
戒情不戒烟
7楼-- · 2019-01-15 08:31

I have fixed the issue of Angular2 HTTP Post ASP.NET MVC Web API

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
let params: URLSearchParams = new URLSearchParams();
params.set('value', '2');

let options = new RequestOptions({
    headers: headers//,
    //search: params
});
let content = new URLSearchParams();
content.set('StudentName', 'Inderjit Singh';
content.set('Mobile', '+919041165398');            
content.set('Nationality', 'Indian');
content.set('AdmissionNo', '6');
content.set('SectionCode', '1');
content.set('Gender', 'Male');
content.set('RegNo', '18585');
content.set('ClassCode', '1');
this.http.post('YOUR_URL', content.toString(), { headers: headers }).map((res: Response) => { console.log("data is==>" + res.text()); }).subscribe();
查看更多
登录 后发表回答