415 - 不支持的媒体类型

时间:2017-06-15 18:10:00

标签: angularjs

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

import { Event, SearchParameters } from './event.model';

@Injectable()
export class EventService {    
    private _url = "http://localhost:36888/api/HealthFairEvents";

    constructor(private _http: Http) {

    }

    getEvents(SearchParameters) {        
        return this._http.post(this._url + "/HealthFairEventSL", SearchParameters).map(res => res.json());
    }

    getEvent(id: number) {        
        return this._http.get(this._url + "/GetHealthFairEvent/" + id).map(res => res.json());
    }

    addEvent(event: any){
        console.log('add');
        console.log(JSON.stringify(event));
        return this._http.post(this._url + "/PostHealthFairEvent", JSON.stringify(event)).map(res => res.json());
    }

    updateEvent(event: Event){
        console.log('update');        
        console.log(JSON.stringify(event));
        return this._http.put(this._url + "/PutHealthFairEvent/" + event.HealthFairEventId, JSON.stringify(event), 

        ).map(res => res.json());
    }
}

看起来我需要发送' Access-Control-Allow-Origin:*'或者带有_http请求的CORS。但我无法做到。我检查了Angular4文档但没有成功。请帮助我。

2 个答案:

答案 0 :(得分:0)

CORS发生在服务器端,客户端唯一必需的标头是内容类型。

示例:

import { Http, Response, Headers, RequestOptions } from '@angular/http';

getEvent(id: number) {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.get(this._url + "/GetHealthFairEvent/" + id, options).map(res => res.json());
    }

在服务器端,要启用CORS,有几种方法可以执行此操作。最简单的方法是在 installing the Microsoft.AspNet.WebApi.Cors package from NuGet.

之后将其添加到您的web.config
  <system.webServer>
   <httpProtocol>
     <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
        <add name="Access-Control-Allow-Methods" value="*" />
        <add name="Access-Control-Allow-Credentials" value="true" />
     </customHeaders>
   </httpProtocol>
</system.webServer>

有关Microsoft的CORS的更多详细信息:https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

答案 1 :(得分:0)

正确答案是,

updateEvent(event: HealthFairEvent){
        console.log('update');        
        console.log(JSON.stringify(event));
        let customHeader = new Headers();
        customHeader.append('Access-Control-Allow-Origin', '*');

        return this._http.put(this._url + "/XX/" + event.HealthFairEventId, event, { headers: customHeader } ).map(res => res.json());        
    }