【问题标题】:Angular 2, typescript post to API model is nullAngular 2,API模型的打字稿为空
【发布时间】:2016-12-02 01:24:00
【问题描述】:

我已经下载了以下项目:http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api。我在 VS2015 和 IIS express 上运行它。该项目很好,但我想用 Angular 2 调用 API。

所以我在 Visual Studio Code 中设置了我的项目,并在 Angular 2 和 TypeScript 中创建了一个项目。当我尝试发布到名为 Register 的 API 方法时,值为 null ?

我的 Visual Studio Code 服务(Angular2)

import { Injectable } from 'angular2/core';

import { Account } from '../account/Account';
import { RegisterBindingModel } from '../account/RegisterBindingModel';
import {Http, Response, Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class AccountService {
    constructor(private _http: Http) {

    }
    
    createAccount(account: Account): Observable<string> {
        console.log('accountService.createAccount');
        let body = JSON.stringify({ account });
        console.log('T1' + body);
      
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

return this._http.post('https://localhost:44305/api/Account/Register', body, options)
                    .map(this.extractData)
                    .catch(this.handleError); 

浏览器错误和发布值:

服务器 API 错误: Error2_In_API_Method

我可以做一个 GET 操作,但我所有的 POST 操作都是 NULL ?

【问题讨论】:

  • 尝试添加 [FromBody] 属性,为:Register([FromBody]RegisterBindingModel model)
  • 不要对账号进行字符串化,直接作为body的参数insttread传递
  • - 当我添加 Register([FromBody]RegisterBindingModel 模型) 时,我在 API 上遇到了同样的错误。对象参数在那里,但它们都是 NULL。 - 如果我不使用 stringify 操作而只是发布帐户,那么孔对象为 NULL,。
  • 我可以看到 Ajax 调用和 Angular CAll 的有效负载有所不同。 Ajax 看起来像这样:{Email: "sd@dr.dk", Password: "Password1!", ConfirmPassword: "Password1!"} ConfirmPassword: "Password1!"电子邮件:“sd@dr.dk”密码:“密码1!”

标签: api razor typescript angular


【解决方案1】:

我发现了以下,不是很有效,但有效的解决方案,我将帐户类对象映射到一个新对象。然后我将新对象字符串化并发布:

    createAccount(account: Account): Observable<string> {

        var obj = { Email: account.Email, Password: account.Password, ConfirmPassword: account.ConfirmPassword };

            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            let body = JSON.stringify(obj);

            return this._http.post('https://localhost:44305/api/Account/Register',  body, options)
                                .map(this.extractData)
                                .catch(this.handleError);
}

对于我在 API 上遇到的第一个错误,我通过更改以下内容解决了它:

Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

然后我可以从 POST 中获取 GetOwinContext()

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 1970-01-01
    • 2017-05-02
    • 2017-12-22
    • 2016-07-23
    • 2017-04-14
    • 2017-12-20
    • 2016-06-06
    • 2017-11-15
    相关资源
    最近更新 更多