我在API Rest项目上遇到了一些问题。为了使用API控制器,我必须成功登录,但是当我更改页面或刷新时,我失去了连接。在Web API中,我已使用HttpContext.Current.Session实现了会话,但无法使用angular访问此会话。可能吗?
我的身份验证控制器:
using Echo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace Echo.Controllers
{
public class AuthController : ApiController
{
private EchoContext db = new EchoContext();
// OPTIONS: api/auth
public IHttpActionResult OptionsAuth()
{
return Ok();
}
public IHttpActionResult GetAuth()
{
if (HttpContext.Current.Session["user"] != null)
{
var u = (User)(HttpContext.Current.Session["user"]);
return Content(HttpStatusCode.OK, new {u.Id,u.Name,u.Mail} );
}
else
{
var e = new CustomResponse();
e.HttpCode = HttpStatusCode.BadRequest;
e.Message = "No user logged in";
return Content(e.HttpCode, e);
}
}
public IHttpActionResult DeleteAuth()
{
if (HttpContext.Current.Session["user"] != null)
{
HttpContext.Current.Session["user"] = null;
var e = new CustomResponse();
e.HttpCode = HttpStatusCode.OK;
e.Message = "Disconnected successfully";
return Content(e.HttpCode, e);
}
else
{
var e = new CustomResponse();
e.HttpCode = HttpStatusCode.BadRequest;
e.Message = "No user logged in";
return Content(e.HttpCode, e);
}
}
[HttpPost]
public IHttpActionResult PostAuth(Auth auth)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (HttpContext.Current.Session["user"] != null)
{
var e = new CustomResponse();
e.HttpCode = HttpStatusCode.Forbidden;
e.Message = "You are already connected";
return Content(e.HttpCode, e);
}
try
{
User u = db.Users.Where(x => x.Name == auth.Name).First();
if (u.Password == auth.Password)
{
HttpContext.Current.Session["user"] = u;
return Ok(new { u.Id, u.Name, u.Mail, u.CreationTime });
}
else
{
var e = new CustomResponse();
e.HttpCode = HttpStatusCode.BadRequest;
e.Message = "wrong credentials";
return Content(e.HttpCode, e);
}
}
catch (Exception)
{
var e = new CustomResponse();
e.HttpCode = HttpStatusCode.BadRequest;
e.Message = "Unknown user";
return Content(e.HttpCode, e);
}
}
}
}
登录后,API即可与PostMan正常工作。
我的组件
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ConnexionService } from '../../services/connexion.service';
import { Router } from '@angular/router';
import { CookieService } from 'angular2-cookie/core';
@Component({
selector: 'app-connexion',
templateUrl: './connexion.component.html',
styleUrls: ['./connexion.component.css']
})
export class ConnexionComponent implements OnInit {
auth = new FormGroup({
Name : new FormControl(''),
Password : new FormControl('')
});
donner: string;
connectedUser: string;
constructor(private service: ConnexionService, private router: Router, private cookie: CookieService) { }
ngOnInit() {
this.connectedUser = localStorage.getItem('user');
}
getAuth() {
const donner = {
'Name': this.auth.controls.Name.value,
'Password': this.auth.controls.Password.value
};
this.Authentification(donner);
}
Authentification(donnerFormulaire: any) {
this.service.envoieConnexion(donnerFormulaire).subscribe(
(data: any) => { /*this.router.navigate(['/ModifierUtilisateur']);*/
localStorage.setItem('user', JSON.stringify(data));
console.log(data); },
error => { console.log(error); }
);
}
}
我的服务:
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Form, NgForm } from '@angular/forms';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ConnexionService {
private loggedInStatus = JSON.parse( localStorage.getItem('loggedin') || 'false');
constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
setLoggedIn(value: any) {
}
get isLoggedIn() {
return JSON.parse(localStorage.getItem('loggedin') || this.loggedInStatus.toString());
}
envoieConnexion(donneeFormulaire: any): any {
const body = JSON.stringify(donneeFormulaire);
return this.http.post('https://echorestapi.azurewebsites.net/api/Auth/', body, this.httpOptions);
}
getConnexion(user: any) {
this.http.get('https://echorestapi.azurewebsites.net/api/Auth/', user);
}
}