意外的令牌<在尝试调用ASP.NET控制器时,在位置0的JSON中

时间:2017-06-04 21:33:37

标签: json asp.net-mvc angular post angular-services

我发现并阅读了许多有关此错误的帖子,但未发现类似或类似问题。 尝试使用角度2中的post从MVC控制器获取数据。

控制器:

[RoutePrefix("")]
public class CategoryController : ApiController
{

    [HttpPost, Route("createNode")]
    public object CreateNode([FromBody]string nodeText)
    {
        return Json( new { nodeText = "test"});
    }
}

组件中的功能

onclickCreateFolder(categoryName: string) {
    this.categoryService.createNode(categoryName).then(result => {
    });

angular-2服务

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Request, RequestMethod, Headers  } from '@angular/http';
import { BaseService } from '../../base/base.service'
import { CategoryViewModel } from '../model/category-tree.model';
import { TreeNode } from 'primeng/primeng';
import 'rxjs/add/operator/toPromise';



@Injectable()
export class CategoryTreeService {
    private apiUrl: string = '/';

    constructor(private baseService: BaseService, private http: Http) {
    }

    createNode(nodeText: string): Promise<any> {
        return this.baseService.post(this.apiUrl + "createNode", JSON.stringify({nodeText}));
    }
}

我正在使用基本服务。以下是发起帖子请求的部分:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Response, RequestOptionsArgs, ResponseContentType } from '@angular/http';
import { Http, RequestOptions, Request, RequestMethod, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

@Injectable()
export class BaseService {
    private headers: Headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Data-Type': 'json' });

    constructor(private http: Http, private router: Router) {
    }

    public post<T>(url: string, body: any, options?: RequestOptionsArgs): Promise<T> {
        return this.http.post(url, body, this.mergeHeaders(options))
            .toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError.bind(this));
    }

    private mergeHeaders(options?: RequestOptionsArgs): RequestOptionsArgs {
        let args = options || {};
        args.headers = args.headers || this.headers;
        return args;
    }

    public handleError(error: any) {
        if (error.status == 400) {
            switch (error.statusText) {
                case "Authentication":
                    this.router.navigate(['/error/auth']);
                    break;
                default:
                    return Promise.reject(error);
            }
            return;
        }
        return Promise.reject(error.toString());
    }
}

我理解错误的原因,因为在回复中我看到了我的单个html页面。另外在调试中我看到ASP.NET控制器中的方法没有被调用。可能是ASP.NET MVC路由中的错误? 已经花了很多时间,但我仍然不明白错误在哪里。我做错了什么?

0 个答案:

没有答案