我正在使用Angular2和MVC 6,我正在尝试调用MVC控制器上的方法来返回数据。
My Angular服务如下:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { ICountry } from '../interfaces/country';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable()
export class RecruiterService {
private _countriesUrl = 'Recruiter/Home/Countries';
constructor(private http: Http) { }
public getCountries = (): Observable<ICountry[]> => {
return this.http.get(this._countriesUrl)
.map((response: Response) => <ICountry[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
//public getCountries = (): Observable<{}> => {
// return this.http.get(this._countriesUrl)
// .map((response: Response) => <any[]>response.json())
// .do(data => console.log('All: ' + JSON.stringify(data)))
// .catch(this.handleError);
//}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
声明了我的ICountry接口:
export interface ICountry {
CountryId: number;
CountryName: string;
ISOCode: number;
}
我的MVC控制器如下:
[Area("Recruiter")]
[Route("Recruiter")]
[Authorize(ActiveAuthenticationSchemes = "Cookie")]
[EnableCors("AllowSpecificOrigin")]
public class HomeController : LogControllerBase<HomeController>
{ .......
[HttpGet("/Home/Countries")]
public IActionResult GetCountries()
{
try
{
//return new JsonResult(new object[] { 1, "England", 3 });
return Ok(_recruiterService.GetAllCountries());
}
catch (Exception ex)
{
Logger.LogError($"Error occured in Recruiter Home/GetCountries: {ex}");
return BadRequest("Obtaining Countries");
}
}......
在我的Angular服务中调用countriesUrl时,我总是收到以下错误,当我换成angular和mvc方法中的注释代码时,我也会得到相同的错误。我从未在MVC控制器方法中达到断点。我还尝试将_countriesURL设置为完全限定的,例如启动http,但我仍然收到相同的错误
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.http.get.map [as project] (recruiter.service.ts:20)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:398)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:397)
at Zone.runTask (zone.js:165)
at XMLHttpRequest.ZoneTask.invoke (zone.js:460)
在浏览器(Chrome)中,如果我转到网络标签,我可以看到对方法的调用,即使它似乎没有断点。在我收到的电话标题中:
Request URL:http://localhost:42413/Recruiter/Home/Countries
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:42413
Referrer Policy:no-referrer-when-downgrade
答案 0 :(得分:0)
我的猜测是你的web api在初始化Controller时有异常。
运行调试器并检查Exception Settings中的所有Common Language Runtime Exceptions
以查看其他任何异常抛出。