如何获取http post以将数据发送到后端。前端是角2,后端是.net 5

时间:2017-01-20 00:33:38

标签: asp.net angular http-post

以下是我遇到的错误:

  

XMLHttpRequest无法加载“http://localhost:49873/api/home”。响应   预检请求未通过访问控制检查:否   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许原点'// localhost:3000'访问。   响应的HTTP状态代码为400。

这是我的控制器:

[EnableCors(origins: "http://localhost:3000", headers: "Access-Control-Allow-Origin", methods: "GET, POST")]
public class HomeController : ApiController
{
    [HttpPost]
    public IHttpActionResult Post([FromBody] book inbook)
    {
        book fromangular = inbook;
        var body = this.Request.Content.ReadAsAsync<book>();
        return Ok(fromangular);
    }
}

这是我的角度2代码:

postBook(inBook: book)
{
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers });
    let x = JSON.stringify(inBook);
    var res = this._http.post(booksUlr, x, { headers }).map((response:                      
                            Response ) => response.json()).subscribe();
    return;
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您是否在WebApi的HttpConfiguration上启用了CORS?我相信您需要明确启用它才能使Controller属性工作。

var config = new HttpConfiguration();
config.EnableCors();

或者您可以在全球范围内启用它。

var config = new HttpConfiguration();
config.EnableCors(new EnableCorsAttribute("http://localhost:3000", "*", "*"));

希望这有帮助。

<强>更新

基于documentation,尝试在声明属性时启用所有方法,然后禁用您不希望授予访问权限的特定操作。

例如

[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
public class HomeController : ApiController
{
    [HttpPost]
    public IHttpActionResult Post([FromBody] book inbook)
    {
        book fromangular = inbook;
        var body = this.Request.Content.ReadAsAsync<book>();
        return Ok(fromangular);
    }
    [DisableCors]
    // some action
}

另外,不确定这是否有帮助,但在文档中''方法:'获取,发布“'是小写的,但这并不能解释为什么get方法正常工作。

相关问题