.NET API不接受" Access-Control-Allow-Origin"来自Angular 2 App

时间:2018-01-15 09:22:25

标签: angular typescript asp.net-web-api asp.net-core

如何将contenty类型设置为application / json格式。

我有一个用于添加客户联系人的帖子方法。 我创建了一个WebAPI,其代码如下......

[Produces("application/json")]
[Route("api/[controller]")]
public class ContactController : Controller
{
    private readonly DatabaseContext _context;
    public ContactController(DatabaseContext context)
    {
        _context = context;
    } 

    [Route("SaveContact")]
    [HttpPost]
    public bool SaveContact(Contact contact)
    {
        return true;
        //var result = _context.Contact.Add(contact);
        //return result == null ? true : false;
    }


    [Route("GetContactList")]
    [HttpGet]
    public List<Contact> GetContactList()
    {
        var result = _context.Contact.ToList();
        return result;
    }
}

我尝试了什么 我已尝试使用POSTMAN和Fiddler工具测试天气我能够将身体发送到api或不下面,以下是POSTMAN和Fiddler的结果:

a. Fiddler: able to send the data (in form of contact model)
[![enter image description here][1]][1]

b. POSTMAN: able to send the data (in form of contact model)    
[![enter image description here][1]][1]

我面临的问题: - 当我尝试通过Angular 2发布帖子请求时,我无法将主体发送到API。我已经尝试了所有的可能性,但对我来说没有任何作用。    这是令人沮丧的,为什么模型没有在api中填充。以下是我如何从Angular 2向API发送请求的详细信息。

  

以下是我提出发布请求的两种不同方式。

import { Headers, Http, HttpModule, RequestMethod, RequestOptions, Response ,Request } from '@angular/http';
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { _App } from "app/app.global"
import { ResponseContentType } from '@angular/http/src/enums';


    @Injectable()
    export class PostService{

        headers:any;
        requestoptions:any;
        constructor(private _http:Http){

       }
        PostMethod2(URL,Body){
            let url:string;
            url = _App._URL;
            const contact = [];
            contact.push(Body);
            console.log(JSON.stringify(contact));
            url = url + URL;
            this.headers = new Headers();
            this.headers.append('Content-Type', 'application/json');
            this.headers.append("Access-Control-Allow-Origin","*");
            console.log(url);
            console.log(this.headers);
            this.requestoptions = new RequestOptions({
                method: RequestMethod.Post,
                url: url,
                headers: this.headers,
                body: JSON.stringify(contact),
                responseType : ResponseContentType.Json,

            })

            return this._http.request(new Request(this.requestoptions))
                .map((res: Response) => {
                    if (res) {
                        debugger;
                        return [{ status: res.status, json: res.json() }]
                    }
                    debugger;
                });

        }

        PostMethod(URL,Body){
            let url : string;
            const contact = [];
            contact.push(Body);

            url = _App._URL + URL;
            this.headers = new Headers();
            this.headers.append('Content-Type', 'application/json');
            this.headers.append("Access-Control-Allow-Origin","*");
            console.log(JSON.stringify(contact));
            console.log(url);
            console.log(this.headers);

            return this._http.post( url,JSON.stringify(contact),{headers:this.headers})
                .map((res: Response) => {
                    if (res) {
                        debugger;
                        return [{ status: res.status, json: res.json() }]
                    }
                    debugger;
                });

        }
    }
  

后方法()

enter image description here

  

Postmethod2()

enter image description here

响应 enter image description here

  

下面是我通过jquery Ajax方法发出的请求,如果你注意到那么你会看到contenty-type的值为application / json,在角度为2的情况下我没有得到。

enter image description here

2 个答案:

答案 0 :(得分:1)

使用Cors。

Install-Package Microsoft.AspNet.WebApi.Cors

App_Start / WebApiConfig - 注册方法:

config.EnableCors();

FooController的:

[EnableCors(origins: "*", headers: "*", methods: "*")]

答案 1 :(得分:0)

除非您需要API公开并被任何域使用,否则您需要允许cors和我的建议在另一个答案中提及*。 而顺便说一句,你不需要额外的包裹

public void ConfigureServices(IServiceCollection services)
{
   var originWhiteList = new[] { ... };
   var methods = new[] { "GET", "PUT", "POST", "DELETE" };
   var headers = new[] { .. };
   services.AddCors(options =>
        {
            options.AddPolicy(
                "MyPolicy",
                builder => builder
                    .WithOrigins(originWhiteList)
                    .WithMethods(methods)
                    .WithHeaders(headers)
                    .AllowCredentials());
        });
   ..... 
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");
    ......
}