.Net Framework 4.5 中的 CORS 问题 Angular 6

CORS issue in .Net Framework 4.5 with Angular 6

我在 .Net Framework 4.5 中创建了 API,它在 Postman 中运行良好,但是当我使用 Angular7 实现时,我们没有得到请求的参数,例如(用户名和密码)在 API.

我已经尝试过这些步骤:

我已经安装了这个包 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"]; // getting Null
            string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null
            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)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
        }
    }
}

我正在使用 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);
        });
    }
}

在UI中你添加了'Content-Type', 'application/json',所以你最好在ActionResult中接受object类型的参数。

试试这个解决方案:

后端:

public IHttpActionResult Login(JObject request)
{
    string username = Convert.ToString(request.SelectToken("Username")) 
    ...
}

UI:

 loginUser(){
    var data = {
      "Username" : '3333',
      "Password" : '123456'
    }
    return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
      console.log(results);
    });
  }

另一种方法是创建模型Class:

public class LoginRequestDTO 
{
   public string Username{ get; set; }

   public string Password{ get; set; }
}

和操作结果:

public IHttpActionResult Login(LoginRequestDTO request)
{
    string username = request.Username;
    ...
}