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
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Http;
- using System.Web.Http.Cors;
- using System.Web.Http.Description;
- using TestData.Models;
-
- namespace TestData.Controllers
- {
-
-
- public class DemoController : ApiController
- {
- [HttpPost]
- [Route("api/Demo/Login")]
- public IHttpActionResult Login(HttpRequestMessage request)
- {
- string username = HttpContext.Current.Request.Form["Username"];
- string pass = HttpContext.Current.Request.Form["Pass"];
- return Ok('Username: ' +username + 'Password :' +pass);
- }
- }
- }
WebApiConfig.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- using System.Web.Http.Cors;
-
- namespace TestData
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
- }
- }
- }
I am using some code of Angular
auth.service.ts
- import { Injectable } from '@angular/core';
- import { HttpClient, HttpHeaders } from '@angular/common/http';
-
- @Injectable({
- providedIn: 'root'
- })
- export class AuthService {
-
- apiUrl : any = 'http://mydomain/api';
-
- constructor(private http : HttpClient) { }
-
- GetHttpHeaders() : HttpHeaders{
- const headers = new HttpHeaders().set('Content-Type', 'application/json');
- return headers;
- }
-
- loginUser(){
- var data = JSON.stringify({
- "Username" : '3333',
- "Pass" : '123456'
- })
- return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
- console.log(results);
- });
- }
- }