8
Answers

CORS issue in .Net Framework 4.5 with Angular 6

Photo of Md Tak

Md Tak

5y
6.9k
1
I have created API in .Net Framework4.5 and It's working fine in Postman but When i implenting with Angular7 then we didn't get Requested Parameters like(Username and Pass) in API. 

I have already tried these steps:

I have already istalled this packege Microsoft.AspNet.WebApi.Cors

DemoController.cs

  1. using Newtonsoft.Json.Linq;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Net;  
  7. using System.Net.Http;  
  8. using System.Threading.Tasks;  
  9. using System.Web;  
  10. using System.Web.Http;  
  11. using System.Web.Http.Cors;  
  12. using System.Web.Http.Description;  
  13. using TestData.Models;  
  14.   
  15. namespace TestData.Controllers  
  16. {  
  17.   
  18.   
  19.     public class DemoController : ApiController  
  20.     {  
  21.         [HttpPost]  
  22.         [Route("api/Demo/Login")]  
  23.         public IHttpActionResult Login(HttpRequestMessage request)  
  24.         {  
  25.             string username = HttpContext.Current.Request.Form["Username"]; // getting Null  
  26.             string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null  
  27.             return Ok('Username: ' +username + 'Password :' +pass);  
  28.         }  
  29.     }  
  30. }  
WebApiConfig.cs 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5. using System.Web.Http.Cors;  
  6.   
  7. namespace TestData  
  8. {  
  9.     public static class WebApiConfig  
  10.     {  
  11.         public static void Register(HttpConfiguration config)  
  12.         {  
  13.             // Web API configuration and services  
  14.   
  15.             // Web API routes  
  16.             config.MapHttpAttributeRoutes();  
  17.   
  18.             config.Routes.MapHttpRoute(  
  19.                 name: "DefaultApi",  
  20.                 routeTemplate: "api/{controller}/{id}",  
  21.                 defaults: new { id = RouteParameter.Optional }  
  22.             );  
  23.             EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");  
  24.             config.EnableCors(cors);  
  25.         }  
  26.     }  
  27. }  

I am using some code of Angular

auth.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';  
  3.   
  4. @Injectable({  
  5.   providedIn: 'root'  
  6. })  
  7. export class AuthService {  
  8.   
  9.   apiUrl : any = 'http://mydomain/api';  
  10.   
  11.   constructor(private http : HttpClient) { }  
  12.   
  13.   GetHttpHeaders() : HttpHeaders{  
  14.     const headers = new HttpHeaders().set('Content-Type''application/json');  
  15.     return headers;  
  16.   }  
  17.   
  18.   loginUser(){  
  19.     var data = JSON.stringify({  
  20.       "Username" : '3333',  
  21.       "Pass" : '123456'  
  22.     })  
  23.     return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {  
  24.       console.log(results);  
  25.     });  
  26.   }  
  27. }  

Answers (8)

2
Photo of Veerendra Annigere
499 2.7k 665.1k 5y
CORS issue is nothing to do with you're coding. Configure CORS where you're API is deployed. You can set origin in you're code.
 
Eg: If You're API is deployed in Azure 
 

 
1
Photo of Madan Shekar
231 8.3k 1.2m 5y
@
Veerendra Annigere
 
thanks for sharing valuable  information...

My question is in case of API's are deployed at Godaddy or some other servers , in such case also we will get same configuratoion section.
1
Photo of Gajendra Jangid
25 41.2k 2.3m 5y
  1. [RoutePrefix("api/Demo")]  
  2. public class DemoController : ApiController    
  3.     {    
  4.         [HttpPost]    
  5.         [Route("Login")]    
  6.         public IHttpActionResult Login(HttpRequestMessage request)    
  7.         {    
  8.             string username = HttpContext.Current.Request.Form["Username"]; // getting Null    
  9.             string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null    
  10.             return Ok('Username: ' +username + 'Password :' +pass);    
  11.         }    
  12.     }   
 
 
0
Photo of Rajeesh Menoth
66 27.1k 2.7m 5y
Hi,
 
Try the following steps.
 
  1. Install CORS to the API project "Install-Package Microsoft.Asp.Net.WebApi.Cors".
  2. Open the App_Start/WebApiConfig.cs file and add the following code to the WebApiConfig.Register method.
First enable the cors then add the remening section I think in your code I am able to see cors enable is done after the route.
  1. using System.Web.Http;    
  2.     
  3. namespace WebServiceApp    
  4. {    
  5.     public static class WebApiConfig    
  6.     {    
  7.         public static void Register(HttpConfiguration config)    
  8.         {    
  9.             //CORS config    
  10.             config.EnableCors();    
  11.             // Web API configuration and services    
  12.     
  13.             // Web API routes    
  14.             config.MapHttpAttributeRoutes();    
  15.     
  16.             config.Routes.MapHttpRoute(    
  17.                 name: "DefaultApi",    
  18.                 routeTemplate: "api/{controller}/{id}",    
  19.                 defaults: new { id = RouteParameter.Optional }    
  20.             );    
  21.         }    
  22.     }    
  23. }    
   3. Add the [EnableCors] attribute to the UserController.
 
Only copy the " [EnableCors(origins: "http://localhost:8578", headers: "*", methods: "*")] " and orgins is nothing but the angular request url domain name. Currently we are tested in the local host so that's why put as localhost url.
  1. namespace WebServiceApp.Controllers    
  2. {    
  3.     [EnableCors(origins: "http://localhost:8578", headers: "*", methods: "*")]    
  4.     public class UserController : ApiController    
  5.     {    
  6.         public HttpResponseMessage GetInfo()    
  7.         {    
  8.             var res = new List<User>() {    
  9.                 new User { ID = 1, Name = "Gopal", Email = "gopal@bitmascot.com" },    
  10.                 new User { ID = 2, Name = "Nayan", Email = "nayan@live.com" },    
  11.                 new User { ID = 3, Name = "Shuvo", Email = "shuvo@live.com" }    
  12.             };    
  13.             return Request.CreateResponse(HttpStatusCode.OK, res);    
  14.         }    
  15.     }    
  16. }   
Reference :
https://www.c-sharpcorner.com/UploadFile/009ee3/implementation-of-cross-origin-request-in-Asp-Net-web-api-2/ 
 
0
Photo of Parth Munjpara
NA 203 36 5y
WebConfig.cs 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace UrbanDB.API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*", "Access-Control-Allow-Origin");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
 
 
And below code just put on controller name Like
 
 [EnableCors("*","*","*")]
public class DemoController : ApiController  
0
Photo of Bidyasagar Mishra
NA 5.3k 379.5k 5y
Go through the below link you will get the solution for 
http://csharp-video-tutorials.blogspot.com/2016/09/cross-origin-resource-sharing-aspnet.html 
0
Photo of Veerendra Annigere
499 2.7k 665.1k 5y
Madan Soraba.
 
No.Configuration varies for different hosting vendors.
 
For Godaddy,

Include a file named .htaccess (notice the leading dot) anywhere in the path of the requested file, that file should contain this line:

Header set Access-Control-Allow-Origin "*". 

My point is CORS issue is nothing to do with frontend. Configuration needed in backend. 
0
Photo of Madan Shekar
231 8.3k 1.2m 5y
 using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")] 
public class LoginController : ApiController
{
//your code 
 
run this nuget package manger 
Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.7

If it helps pls mark as answer.