How to pass the headers separatelyin angular4(when passing json object to API not working)

103 views Asked by At

Here I'm trying to catch and save some data to DB (post method)using angular 4.when clicking the confirm button got an error like blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

when trying to postman I got the output.so i confirm my Web APi is working fine. actually I am new in angular so i think my problem is in typescript or angular service. I want the output like this.

 { 
"Header": {

            "UserID": 6,
           "created": "February 4, 2016 10:13:00",
            ....etc........
         },

  "detail": [
    {

      "ShopID": 1,
     "ItemID": 126,
    .....etc.........
   },
  {     
  "ShopID": 1,
   "ItemID": 127,
   .....etc.........
    }
  ]
 }

This is my typescript file

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

This is my angularservice.ts file

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

startup.cs file

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

}
}
}

my 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;
    }
3

There are 3 answers

4
Ameerudheen.K On

Go to your startup.cs file and add this into your Configure method.

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

After that edit your ConfigureServices method with :-

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

Now try running your application

3
Nandan On

Include EnableCors in your WebApiConfig, this should work

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

For more reference see :https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

5
Amey On

add this line in your webApiConfig

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

It will work

Still If You need to add header in angular you can refer the below code :-

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

send these httpOptions to post , get request that you are making

in your Code You can Do this also : - Replace the headers line with this

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