如何在 angular4 中单独传递标头(将 json 对象传递给 API 不起作用时)



在这里,我尝试使用角度捕获一些数据并将其保存到数据库(发布方法(4.当单击确认按钮时出现错误,例如被CORS策略阻止: 对预检请求的响应未通过访问控制检查:请求的资源上不存在"访问控制-允许源"标头。

当尝试邮递员时,我得到了 output.so 我确认我的 Web APi 工作正常。 实际上我是 angular 的新手,所以我认为我的问题出在打字稿或 angular 服务中。我想要这样的输出。

{ 
"Header": {
"UserID": 6,
"created": "February 4, 2016 10:13:00",
....etc........
},
"detail": [
{
"ShopID": 1,
"ItemID": 126,
.....etc.........
},
{     
"ShopID": 1,
"ItemID": 127,
.....etc.........
}
]
}

这是我的打字稿文件

stockitems: IStockCountHeaders[] = [];   
items: IStockCountHeaders;
stockdetail: IStockdetails[] = [];
addItems(value: any) {
this.items = new IStockCountHeaders(this.userid, this.created, t this.confirm,this.shopid, 
value.ItemID, value.PackingTypeID, value.ItemCode, value.ItemDescription, 
value.PackingtypeName, 
value.Stock,
);
this.stockitems.push(this.items);
}
onclick(){
this._enqService.CatchStockDetailHeader(this.stockitems)
.subscribe(value => {
if (typeof value !== 'undefined' && value != null) {
value.forEach(items => {
this.stockitems.push(this.items)
});
}
},
error => {
console.error(error);
this.statusMessage = "Problem with the service.Please try again after sometime";
});
}

这是我的angularservice.ts文件

CatchStockDetailHeader(stock: any)
: Observable<IStockCountHeaders[]> {
let IStockCounts = stock;  
console.log(IStockCounts)
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
headers.append('userid', IStockCounts.userid);
headers.append('created', IStockCounts.created);
headers.append('.CompanyID', IStockCounts.CompanyID);
headers.append('modified', IStockCounts.modified);
headers.append('modifieduserid', IStockCounts.modifieduserid);
headers.append('confirm', IStockCounts.confirm);    
return this._http.post('http://localhost:3071/api/Stockcountheader/' + 'Stock', IStockCounts, options)
.map((response: Response) => <IStockCountHeaders[]>response.json())
.catch(this.handleError);
}

启动.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebAPIService.Startup))]
namespace WebAPIService
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}

我的接口

public class StockClass
{
public spGetNewStockCountHeader_Result header { get; set; }
public List<spGetNewStockCountDetails_Result> detail { get; set; }
}
public class StockcountheaderController : ApiController
{
private adminv2Entities enqentities = new adminv2Entities();
HttpSessionState session = HttpContext.Current.Session;
[HttpPost]
public IHttpActionResult Stock([FromBody] StockClass obj)
{
spGetNewStockCountHeader_Result stockheader = new spGetNewStockCountHeader_Result();
int schid = enqentities.spGetNewStockCountHeader(obj.header.UserID, obj.header.created, obj.header.CompanyID, obj.header.modified, obj.header.modifieduserid, obj.header.confirm, obj.header.ShopId).FirstOrDefault().Schid;
foreach (var Stockobject in obj.detail)
{
enqentities.spGetNewStockCountDetails(Stockobject.ShopID, Stockobject.ItemID, Stockobject.PackingTypeID, Stockobject.Itemcode, Stockobject.Itemdescription, Stockobject.PackingtypeName, Stockobject.Stockcount, schid);
}
return Ok();
}

public StockClass getStock()
{
StockClass obj = new StockClass();
spGetNewStockCountHeader_Result tmphd = new spGetNewStockCountHeader_Result();
obj.header = tmphd;
List<spGetNewStockCountDetails_Result> tmplist = new List<spGetNewStockCountDetails_Result>();
spGetNewStockCountDetails_Result tmp = new spGetNewStockCountDetails_Result();
tmplist.Add(tmp);
obj.detail = tmplist;
return obj;
}

转到您的 startup.cs 文件并将其添加到您的配置方法中。

app.UseCors(options => options.AllowAnyOrigin());

之后,使用 :- 编辑您的ConfigureServices方法

services.AddCors(c =>  
{  
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
});

现在尝试运行您的应用程序

在你的 WebApiConfig 中包含 EnableCors,这应该可以工作

using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

有关更多参考,请参阅 :https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

在webApiConfig中添加此行

var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);

它会工作

仍然如果您需要在角度中添加标题,您可以参考以下代码:-

let httpOptions = new HttpHeaders() ; 
.set('Access-Control-Allow-origin','*')

发送这些 httpOptions 以发布 ,获取您正在发出的请求

在你的代码中,你也可以这样做:- 将标题行替换为此

let headers = new HttpHeaders({'Content-Type':'application/json','Access-Control-Allow-Origin':'*'})

相关内容

  • 没有找到相关文章

最新更新