ASP.NET Core mit Angular

  • C# (ASP)

Es gibt 2 Antworten in diesem Thema. Der letzte Beitrag () ist von Niko77.

    ASP.NET Core mit Angular

    Hallo zusammen,Ich habe vor mir über den Winter eine kleine Web App zu basteln, bin aber Anfänger.Habe mit Visual Studio 2022 ein Projekt mit der Vorlage ASP.NET Core mit Angular erstellt. Als Authentifizierungstyp habe ich Einzelne Konten gewählt.Nun habe ich Im Backend ein simples Modul für Produckte und ein Controller HttpGet..POST…Put..usw. gemacht. Das ganze habe ich mit Postman getestet und ich kann alle Aktionen ausführen.Dann hab ich in Angular eine Komponente (Lager) erstellt, einen Service , eine Component und eine Html.Nun versuche ich ein POST abzusetzen der mir die Daten an das backend sendet, doch wird er vorher in Angular schon abgefangen und ich bekomme POST localhost:7199/api/lager 400 (Bad Request) authorize.service.ts:63Ich weiß das es mit der authorize zu tun haben muss, doch schnalle ich noch nicht wie ich das hinbekommen soll.

    Lger.component

    Quellcode

    1. import { Component } from '@angular/core';
    2. import { LagerService } from './lager.service';
    3. @Component({
    4. selector: 'app-lager',
    5. templateUrl: './lager.component.html',
    6. })
    7. export class LagerComponent {
    8. constructor(private lagerService: LagerService) { }
    9. datenHochladen(): void {
    10. const hartcodierteDaten = [
    11. { Name: 'Produkt 1', Menge: 10 }
    12. ];
    13. this.lagerService.datenHochladen(hartcodierteDaten).subscribe(
    14. response => {
    15. console.log('Daten erfolgreich hochgeladen:', response);
    16. },
    17. error => {
    18. console.error('Fehler beim Hochladen der Daten:', error);
    19. }
    20. );
    21. }
    22. }


    lager.service

    Quellcode

    1. import { Inject, Injectable } from '@angular/core';
    2. import { HttpClient, HttpHeaders } from '@angular/common/http';
    3. import { Observable } from 'rxjs';
    4. @Injectable({
    5. providedIn: 'root'
    6. })
    7. export class LagerService {
    8. constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }
    9. public datenHochladen(daten: any): Observable<any> {
    10. const headers = new HttpHeaders().set('Content-Type', 'application/json');
    11. console.log('Daten werden hochgeladen:', { headers: headers });
    12. return this.http.post<any>('https://localhost:7199/api/lager', JSON.stringify(daten), { headers: headers })
    13. }
    14. }


    Code-Tags korrigiert, Topic verschoben. ~Thunderbolt

    Dieser Beitrag wurde bereits 2 mal editiert, zuletzt von „Marcus Gräfe“ ()

    Der ist bei der Projektvorlage schon dabei und sieht so aus.

    Quellcode

    1. import { Injectable } from '@angular/core';
    2. import { User, UserManager } from 'oidc-client';
    3. import { BehaviorSubject, concat, from, Observable } from 'rxjs';
    4. import { filter, map, mergeMap, take, tap } from 'rxjs/operators';
    5. import { ApplicationPaths, ApplicationName } from './api-authorization.constants';
    6. export type IAuthenticationResult =
    7. SuccessAuthenticationResult |
    8. FailureAuthenticationResult |
    9. RedirectAuthenticationResult;
    10. export interface SuccessAuthenticationResult {
    11. status: AuthenticationResultStatus.Success;
    12. state: any;
    13. }
    14. export interface FailureAuthenticationResult {
    15. status: AuthenticationResultStatus.Fail;
    16. message: string;
    17. }
    18. export interface RedirectAuthenticationResult {
    19. status: AuthenticationResultStatus.Redirect;
    20. }
    21. export enum AuthenticationResultStatus {
    22. Success,
    23. Redirect,
    24. Fail
    25. }
    26. export interface IUser {
    27. name?: string;
    28. }
    29. @Injectable({
    30. providedIn: 'root'
    31. })
    32. export class AuthorizeService {
    33. static getAccessToken() {
    34. throw new Error('Method not implemented.');
    35. }
    36. private popUpDisabled = true;
    37. private userManager?: UserManager;
    38. private userSubject: BehaviorSubject<IUser | null> = new BehaviorSubject<IUser | null>(null);
    39. public isAuthenticated(): Observable<boolean> {
    40. return this.getUser().pipe(map(u => !!u));
    41. }
    42. public getUser(): Observable<IUser | null> {
    43. return concat(
    44. this.userSubject.pipe(take(1), filter(u => !!u)),
    45. this.getUserFromStorage().pipe(filter(u => !!u), tap(u => this.userSubject.next(u))),
    46. this.userSubject.asObservable());
    47. }
    48. public getAccessToken(): Observable<string | null> {
    49. return from(this.ensureUserManagerInitialized())
    50. .pipe(mergeMap(() => from(this.userManager!.getUser())),
    51. map(user => user && user.access_token));
    52. }
    53. public async signIn(state: any): Promise<IAuthenticationResult> {
    54. await this.ensureUserManagerInitialized();
    55. let user: User | null = null;
    56. try {
    57. user = await this.userManager!.signinSilent(this.createArguments());
    58. this.userSubject.next(user.profile);
    59. return this.success(state);
    60. } catch (silentError) {
    61. console.log('Silent authentication error: ', silentError);
    62. try {
    63. if (this.popUpDisabled) {
    64. throw new Error('Popup disabled. Change \'authorize.service.ts:AuthorizeService.popupDisabled\' to false to enable it.');
    65. }
    66. user = await this.userManager!.signinPopup(this.createArguments());
    67. this.userSubject.next(user.profile);
    68. return this.success(state);
    69. } catch (popupError: any) {
    70. if (popupError.message === 'Popup window closed') {
    71. return this.error('The user closed the window.');
    72. } else if (!this.popUpDisabled) {
    73. console.log('Popup authentication error: ', popupError);
    74. }
    75. try {
    76. await this.userManager!.signinRedirect(this.createArguments(state));
    77. return this.redirect();
    78. } catch (redirectError: any) {
    79. console.log('Redirect authentication error: ', redirectError);
    80. return this.error(redirectError);
    81. }
    82. }
    83. }
    84. }
    85. public async completeSignIn(url: string): Promise<IAuthenticationResult> {
    86. try {
    87. await this.ensureUserManagerInitialized();
    88. const user = await this.userManager!.signinCallback(url);
    89. this.userSubject.next(user && user.profile);
    90. return this.success(user && user.state);
    91. } catch (error) {
    92. console.log('There was an error signing in: ', error);
    93. return this.error('There was an error signing in.');
    94. }
    95. }
    96. public async signOut(state: any): Promise<IAuthenticationResult> {
    97. try {
    98. if (this.popUpDisabled) {
    99. throw new Error('Popup disabled. Change \'authorize.service.ts:AuthorizeService.popupDisabled\' to false to enable it.');
    100. }
    101. await this.ensureUserManagerInitialized();
    102. await this.userManager!.signoutPopup(this.createArguments());
    103. this.userSubject.next(null);
    104. return this.success(state);
    105. } catch (popupSignOutError: any) {
    106. console.log('Popup signout error: ', popupSignOutError);
    107. try {
    108. await this.userManager!.signoutRedirect(this.createArguments(state));
    109. return this.redirect();
    110. } catch (redirectSignOutError: any) {
    111. console.log('Redirect signout error: ', redirectSignOutError);
    112. return this.error(redirectSignOutError);
    113. }
    114. }
    115. }
    116. public async completeSignOut(url: string): Promise<IAuthenticationResult> {
    117. await this.ensureUserManagerInitialized();
    118. try {
    119. const response = await this.userManager!.signoutCallback(url);
    120. this.userSubject.next(null);
    121. return this.success(response && response.state);
    122. } catch (error: any) {
    123. console.log(`There was an error trying to log out '${error}'.`);
    124. return this.error(error);
    125. }
    126. }
    127. private createArguments(state?: any): any {
    128. return { useReplaceToNavigate: true, data: state };
    129. }
    130. private error(message: string): IAuthenticationResult {
    131. return { status: AuthenticationResultStatus.Fail, message };
    132. }
    133. private success(state: any): IAuthenticationResult {
    134. return { status: AuthenticationResultStatus.Success, state };
    135. }
    136. private redirect(): IAuthenticationResult {
    137. return { status: AuthenticationResultStatus.Redirect };
    138. }
    139. private async ensureUserManagerInitialized(): Promise<void> {
    140. if (this.userManager !== undefined) {
    141. return;
    142. }
    143. const response = await fetch(ApplicationPaths.ApiAuthorizationClientConfigurationUrl);
    144. if (!response.ok) {
    145. throw new Error(`Could not load settings for '${ApplicationName}'`);
    146. }
    147. const settings: any = await response.json();
    148. settings.automaticSilentRenew = true;
    149. settings.includeIdTokenInSilentRenew = true;
    150. this.userManager = new UserManager(settings);
    151. this.userManager.events.addUserSignedOut(async () => {
    152. await this.userManager!.removeUser();
    153. this.userSubject.next(null);
    154. });
    155. }
    156. private getUserFromStorage(): Observable<IUser | null> {
    157. return from(this.ensureUserManagerInitialized())
    158. .pipe(
    159. mergeMap(() => this.userManager!.getUser()),
    160. map(u => u && u.profile));
    161. }
    162. }

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „Niko77“ ()