Как отправить данные форм в ASP. NET Базовое действие Web API, украшенное [FromForm] в Angular? - PullRequest
0 голосов
/ 29 февраля 2020

Вот мое действие в asp core api:

[Route("[action]"), HttpPost]
[AllowAnonymous]
public async Task<ActionResult> GenerateToken([FromForm]OAuthTokenRequestDto tokenRequest, CancellationToken cancellationToken)
{
    // Some Code
}

OAuthTokenRequestDto:

public class OAuthTokenRequestDto
{
    public string grant_type { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string refresh_token { get; set; }
    public string scope { get; set; }

    public string client_id { get; set; }
    public string client_secret { get; set; }
}

И это мой Login.Component. html:


<form class="form-signin" #f="ngForm" (ngSubmit)="signIn(f.value)">

<input type="username" id="inputEmail" name="username" ngModel class="form-control" placeholder="username" required autofocus>

<input type="password" id="inputPassword" name="password" ngModel class="form-control" placeholder="Password" required>


<input type="client_id" id="inputclient_id" name="client_id" ngModel class="form-control" >

<input type="refresh_token" id="inputrefresh_token" name="refresh_token" ngModel class="form-control" >

<input type="scope" id="inputscope" name="scope" ngModel class="form-control" >

<input type="client_secret" id="inputclient_secret" name="client_secret" ngModel class="form-control" >

<input type="grant_type" id="inputgrant_type" name="grant_type" ngModel class="form-control" placeholder="password">

  <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>

Login.Component.ts:

import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Component } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  invalidLogin: boolean;

  constructor(
    private router: Router,
    private http: HttpClient
    ) { }

  signIn(credentials) {
    return this.http.post('/api/Users/GenerateToken', 
      new OAuth(credentials.username,credentials.password)
        )
      .subscribe(result => {
        if (result)
          this.router.navigate(['/']);
        else
          this.invalidLogin = true;
      });
  }
}

class OAuth {
  grant_type : string;
  username   : string;
  password   : string;
  refresh_token : string;  
  scope   : string;

  client_id   : string;
  client_secret : string;

  constructor (username: string, password : string)
  {
    this.username = username;
    this.password = password;
    this.client_id = "";
    this.refresh_token = "";
    this.scope = "";
    this.client_secret = "";
    this.grant_type = "password";
  }
}

Когда я пытаюсь опубликовать учетные данные для действия, я получаю ошибку 415, но когда я удаляю [FromForm] из действия, это работает.

Я не знаю, в чем проблема.

Обратите внимание : я хочу, чтобы на моем действии было [FromForm]

1 Ответ

1 голос
/ 02 марта 2020

Если вы хотите отправить данные через поля формы, попробуйте следующий фрагмент кода.

signIn(credentials) {
  const formData = new FormData();
  formData.append("username", credentials.username);
  formData.append("password", credentials.password);
  // other fields

  return this.http
    .post("/api/Users/GenerateToken", formData)
    .subscribe(result => {
      //code logic here
    });
}

Результат теста

enter image description here

...