为什么我的ASP.NET Web API路由可与Postman一起使用但不能与Angular Post请求一起使用 [英] Why is my ASP.NET Web API route working with Postman but not working with Angular Post request

查看:135
本文介绍了为什么我的ASP.NET Web API路由可与Postman一起使用但不能与Angular Post请求一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是怎么回事.我有一个使用ASP.NET Web API的POST路由,该路由应该更改SQL Server中的某些数据.当我使用Postman测试我的REST API时,它可以工作,并且数据库中的数据已更改,并且响应正常.但是一旦我使用Angular5将json发布到相同的数据库,它就会响应并显示错误405.这是我的代码...

I have no idea what's going on here. I have a POST route using ASP.NET web API that should change some data in my SQL Server. When I use Postman to test out my REST API it works and the data is changed in the database and the response is okay. But once I use Angular5 to post json to the same database it responds with error 405. Here is my code...

首先,这是我的MVC应用中的POST路由.

First, here is the POST route from my MVC app.

// POST api/<controller>
[Route("")]
[HttpPost]
public HttpResponseMessage Post([FromBody]BranchesInfo data)
{
    BranchesDB.updateBranchRow(data);
    var response = Request.CreateResponse<BranchesInfo>(HttpStatusCode.OK,data);
    return response;
}

邮递员的回复在下一张图片中.数据已在数据库中成功更改,尽管它与发送的信息没有关联,因为在updateBranchRow()函数中调用的存储过程不响应任何资源,因此我组成了该资源以返回传递的相同数据内.

The response from Postman is in the next image. The data is successfully changed in the database although it has no correlation to the info being sent in as my Stored Procedure that's called in the updateBranchRow() function does not respond with any resource, so I made up the resource to return the same data passed in.

在这里您可以看到请求已收到并且可以在PostMan中成功工作

Here you can see that the request is recieved and works successfully in PostMan

现在,这是我的Angular代码,它使用服务来发布数据.

Now, here is my Angular code which uses a service to post the data.

host: string = "http://localhost:57440/api/branches";

updateBranch(branchKey: Number, mainBranch: String, branchRegion: String, mainBranchFlag: Boolean) {
  var data = {
    BranchKey: branchKey,
    BranchName: mainBranch,
    BranchRegion: branchRegion,
    MainBranchFlag: mainBranchFlag
  }
  return this.http.post(this.host, data).map(res => res.json());
});

这是我尝试记录收到的响应后在浏览器控制台上遇到的错误的图像.

And here is an image of the error I am getting on the browser console once I try to log the response recieved.

在浏览器控制台上的响应:

Response on the browser console:

我真的不明白我在做什么错.基于REST的请求如何与Postman一起使用,而在使用Angular4时却不起作用?

I really don't understand what I'm doing wrong. How can a REST based request work with Postman but not work when using Angular4??

推荐答案

在Global.asax.cs文件中添加以下代码

In Global.asax.cs file add following code

protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }

这篇关于为什么我的ASP.NET Web API路由可与Postman一起使用但不能与Angular Post请求一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆