简体   繁体   中英

model binding fails on POST

I have an ASP.Net Core 2.0 project that I'm using as a web api. The client-side is done with Angular 4. When I post my form data from my angular service to my API, the model properties on the server-side are always null. I'm not sure what I'm doing wrong here. I've tried various combinations of using application/json and application/x-www-form-urlencoded . I've also tried both [FromBody] and [FromForm] attributes and in both cases the properties on my model are null.

Am I doing something wrong on the angular side during my post?

在此处输入图片说明

I've verified that my json string being posted (shown in the screenshot) contains my expected form data. It arrives null on the server though.

This is my angular service

import { Injectable, OnInit } from '@angular/core';
import { Http, URLSearchParams, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/mergeMap';

import { CryptoData } from './cryptodata.interface';
import { Result } from './result.model';

@Injectable()
export class EncryptService implements OnInit {
    private options: RequestOptions;

    constructor(private http: Http) {
        this.options = new RequestOptions({
                headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' })
            })
    }

    ngOnInit() {
    }

    encrypt(data: CryptoData): Promise<Result> {
        let json: any = JSON.stringify(data);

        return this.http
        .post('/api/encrypt', json, this.options)
        .toPromise()
        .then(response => response.json());
    }

    decrypt(data: CryptoData) {

    }
}

This is my controller:

[Produces("application/json")]
[AllowAnonymous]
public class CryptoController : Controller
{
    [HttpPost("~/api/Encrypt")]
    public IActionResult Encrypt([FromForm] CryptoRequest request)
    {
        // Testing
        return base.Ok(new Result(data: request.Content));
    }
}

[FromBody] and Content-Type: application/json works very well for me with the same request in asp net core. I sent data from plugin in firefox: { "key" : "1", "content" : "cont" }

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM