-1

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;
    }
Brock James
  • 196
  • 1
  • 11

3 Answers3

0

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

Ameerudheen.K
  • 657
  • 1
  • 11
  • 31
0

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

Nandan
  • 172
  • 8
  • Yes, with postman you'll get. But browser you'll get preflight if you don't have CORS enabled – Nandan Sep 18 '19 at 04:37
  • Did you add this like on top of your controller [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")] – Nandan Sep 18 '19 at 04:37
  • Check this link and follow the steps: https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors – Nandan Sep 18 '19 at 04:38
0

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':'*'})
Amey
  • 795
  • 8
  • 31
  • @BrockJames this is server side issue you dont need to add any code in angular – Amey Sep 18 '19 at 05:44
  • Do you check my angular code?if any problem is there? – Brock James Sep 18 '19 at 05:49
  • got error Severity Code Description Project File Line Suppression State Error CS0144 Cannot create an instance of the abstract class or interface 'HttpHeaders' – Brock James Sep 18 '19 at 05:54
  • @BrockJames Have you added the above code in webapi also ? as its mainly server side issue – Amey Sep 18 '19 at 06:01
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199600/discussion-between-brock-james-and-amey). – Brock James Sep 18 '19 at 06:03