-1

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

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

 { 
"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);

}
}
}

我的 API

    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;
    }
4

3 回答 3

0

在您的 webApiConfig 中添加这一行

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

它会工作

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

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

将这些 httpOptions 发送到 post ,获取您正在发出的请求

在你的代码中你也可以这样做: - 用这个替换标题行

let headers = new HttpHeaders({'Content-Type':'application/json','Access-Control-Allow-Origin':'*'})
于 2019-09-18T05:38:24.453 回答
0

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

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

之后编辑你的ConfigureServices方法: -

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

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

于 2019-09-18T04:13:42.933 回答
0

在您的 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 ://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

于 2019-09-18T04:28:03.183 回答