【问题标题】:How do I get http post to send data to backend. front end is angular 2 and backend is .net 5如何获取 http post 以将数据发送到后端。前端是 Angular 2,后端是 .net 5
【发布时间】:2017-01-20 00:33:38
【问题描述】:

这是我得到的错误:

XMLHttpRequest 无法加载“http://localhost:49873/api/home”。回复 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。 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);
    }
}

这是我的 Angular 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;
}

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net angular http-post


    【解决方案1】:

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

    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,post”是小写的,但这并不能解释为什么 get 方法可以正常工作。

    【讨论】:

    • 是的,我确实允许这样做。奇怪的是 GET 方法有效,但 POST 拒绝工作。
    猜你喜欢
    • 2019-01-25
    • 2021-04-28
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多