简体   繁体   中英

How can I access parameters from a POST (or other HTTP) request in a C# server?

I'm building a Reactjs application using ASP.Net Core, and I'm completely new to this. I have a JS component that (to the best of my knowledge) is making an appropriate fetch request (POST) to a C# server controller. The server is definitively receiving the request. However, I have absolutely no idea how to access the parameters of the request (which I am passing through the body).

I've tried using [FromBody] to access the body directly. I've also tried to utilize the Request.Body, the Request.Form, the Request.Query, the Request.Params, etc. I've attempted to follow the guidelines I've found online that seem to try to address my problem. Several of them flat-out haven't worked. Most of them are using key words, classes, etc. that are not available to me in my current libraries, and they don't list the appropriate libraries. For all I know, I've stumbled across the right answer already. But for someone like me with a highly logical mind but also pretty much zero experience in the field, I can't wrap my mind around any of it.

My POST request using fetch in JavaScript:

fetch('api/Database/PushStatus',
    {
        method: 'post',
        headers: { 'Content-type': 'application/json' },
        body: JSON.stringify({ order: this.state.orderNum, status: this.state.newStatus })
    }
).then(response => {
    response.json().then(data => {
        this.setState({ reqCheck: "" + response, didPush: false });
    })
}).catch(err => {
    this.setState({ reqCheck: "Failure! (js)", didPush: false })
});

And my request handling on my C# server:

[Route("api/[controller]/[action]")]
public class DatabaseController : Controller
{
    string conStri = "Data Source=ADM293\\MSSQLSERVER01;Initial Catalog=testDB;User ID=sa;Password=password.1";
    SqlConnection cnct = null;

    [HttpPost]
    public void PushStatus(string order, string status)
    {
        cnct = new SqlConnection(conStri);
        SqlCommand command = new SqlCommand("insert into testTable values ('" + order + "', '" + status + "');", cnct);

        using (cnct)
        {
            cnct.Open();
            int result = command.ExecuteNonQuery();
            cnct.Close();
        }
    }
}

I would like my server to be updated with the contents of this.state.orderNum and this.state.newStatus . Instead, my server is updated with empty string values (which makes perfect sense).

You can create a class that represents the request:

public class PushStatusRequest
{
    public string Order { get; set; }
    public string Status { get; set; }
}

And use it like this:

[HttpPost]        
public void PushStatus([FromBody] PushStatusRequest request){
   //request.Status
   //request.Order
}

@Anteo is right. But I would like to add some explanation. You have faced two different ways to pass params to a controller. You try to use a body (setting body in request) as an entrance and the query (in the controller) as an output.

Well, body is one type and it requires to be some model on a Controller side. Use [FromBody] to automatically retrieve your data from a request into a model. Create this model as a separate class following the same naming politics (ignoring case).

Then, a query string is what you are using at the controller side. On a request side, it follows the URL like this: https://host:port/route/to/then/query/params . So, if I am not mistaking a base URL is a part https://host:port . Everything is left is a query string . A part of that is being mapped to the route to your controller's action. Anything left is interpreted as useful info and mapped to an action params.

So, here is the moment for you to choose (depending on the length of your orderNum and newStatus ) which approach to use. I would recommend using the body as it is more data than routing.

Also, If you inherit [ControllerBase][1] , then you can use Request property in action to access the request itself. But be careful here.

PS I would recommend you to read more about requests, things like form data, body, queries, etc.

If have any further questions feel free to ask.

By default, capitalization changes between JavaScript and C#. So, you probably just need to change your method signature:

public void PushStatus(string Order, string Status)

That said, having the class the way @Anteo suggested is usually better. Also, I assume you put SqlConnection just for clarity. You shouldn't do it in the controller

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