Home > Blockchain >  No Body Data Being Passed using .NET CORE 6
No Body Data Being Passed using .NET CORE 6

Time:07-03

I'm migrating my code from .NET to .NET Core 6 and have hit a brick wall and googling doesn't seem to have helped so any advice, pointers will be welcome.

All of this works in .NET so it's clearly my understanding of how to migrate the API.

I am using a greasemonkey script to scrape some data and pass it to my site.

function sendHome() {
    console.log(window.eval('window.PA_intel'));
    GM.xmlHttpRequest({
        method: "POST",
        url: "https://localhost:7223/api/Parsing/Any",
        data: "{ Data: '"   JSON.stringify(window.eval('window.PA_intel'))   "', Type: 'Intel'}",
        headers: { "Content-Type": "application/json" },
        onl oad: function (response) { console.log(response); toastr["success"]("Intel sent home!", "Phoenix"); },
        one rror: function (reponse) {console.log("error: ", reponse)},
    });

}

This grabs the data from a page an pushes it to an API route that is waiting on api/Parsing/Any

The debug and postman can trigger the API controller so I know the routing works but the body (Data and Type from the GM script) isn't coming with it.

I have a defined model to receive the data

    public class ParseData
    {
        public string Data { get; set; }
        public string Type { get; set; }
    }

and my controller is set up to expect it, but in .NET CORE 6 it's just coming up null

    [Route("api/Parsing/")]
    public class ParsingAPIController : Controller
    {

        [Route("Any")]
        public List<ParseResult> ParseAny(ParseData parseData)
        //public List<ParseResult> ParseAny(string Data, string Type)

        {

As I said the routing is being triggered but the parseData object is null and if I inpsect ParseAny to see what has been sent, I get an error with null body.

Any ideas where I am going wrong?

CodePudding user response:

You can try using the tag [FromBody] with the ParseData parameter.

CodePudding user response:

Actually you need to do 2 things:

  1. Add [ParseBody] to your parameter.

  2. Add [HttpPost] as annotation to your method so that it accepts post requests and gets the post body in the request. Finally your code should be like below:

     [Route("api/Parsing/")]
     public class ParsingAPIController : Controller
     {
    
         [Route("Any")]
         [HttpPost]
         public List<ParseResult> ParseAny([FromBody]ParseData parseData)
         {
    
  • Related