Home > other >  Call .NET Core API from AngularJS using $https - 400 Bad Request
Call .NET Core API from AngularJS using $https - 400 Bad Request

Time:11-06

I'm trying to call a .NET Core API from AngularJS. In the AngularJS I'm calling the method like this:

$http({
      method: 'POST',
      url: '/api/message/transaction/'   this.transaction.id,
      data: { "transactionJson": "hello"}
    })
    .then(function (response) {
                                var r = response;
    })

My .NET Core API method is like this:

    [Route("~/api/message/transaction/{transactionId}")]
    [HttpPost]
    public async Task<ActionResult<DeviceEventsTransactionmsg>> PostTransaction([FromBody] string transactionJson)
    {

I'm getting a 400 Bad Request response back from the server. How do I fix it?

CodePudding user response:

I realised the type for the parameter must be a type that has a property named TransactionJson, so I need to define a new C# type:

public class TransactionData() {
    public string TransactionJson
}

Then in the API method:

[Route("~/api/message/transaction/{transactionId}")]
[HttpPost]
public async Task<ActionResult<DeviceEventsTransactionmsg>> PostTransaction([FromBody] TransactionData transactionJson)
{

CodePudding user response:

getting a 400 Bad Request response back from the server. How do I fix it?

To fix the issue, as your mentioned, one solution is modifying action parameter, like below.

public async Task<ActionResult<DeviceEventsTransactionmsg>> PostTransaction([FromBody] TransactionData transactionJson)
{
    //...
    //code logic here

TransactionData class

public class TransactionData
{
    public string TransactionJson { get; set; }
}

Besides, we can also implement and use a custom plain text input formatter to make PostTransaction action method that accepts a string-type ACTION parameter work well.

public class TextPlainInputFormatter : TextInputFormatter
{
    public TextPlainInputFormatter()
    {
        SupportedMediaTypes.Add("text/plain");
        SupportedEncodings.Add(UTF8EncodingWithoutBOM);
        SupportedEncodings.Add(UTF16EncodingLittleEndian);
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        string data = null;
        using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
        {
            data = await streamReader.ReadToEndAsync();
        }
        return InputFormatterResult.Success(data);
    }
}

Add custom formatter support

services.AddControllers(opt => opt.InputFormatters.Insert(0, new TextPlainInputFormatter()));

Test Result

enter image description here

  • Related