最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

I'm building a Reactjs application using ASP.Net Core, and I'm pletely new to this. I have a JS ponent 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 mand = new SqlCommand("insert into testTable values ('" + order + "', '" + status + "');", cnct);

        using (cnct)
        {
            cnct.Open();
            int result = mand.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).

I'm building a Reactjs application using ASP.Net Core, and I'm pletely new to this. I have a JS ponent 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 mand = new SqlCommand("insert into testTable values ('" + order + "', '" + status + "');", cnct);

        using (cnct)
        {
            cnct.Open();
            int result = mand.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).

Share Improve this question asked May 13, 2019 at 22:14 AnsleanAnslean 411 silver badge10 bronze badges 1
  • Request.QueryString produces an empty string, as does HttpContext.Request.QueryString, just in case that matters. – Anslean Commented May 13, 2019 at 22:24
Add a ment  | 

3 Answers 3

Reset to default 3

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 remend 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.

P.S. I would remend 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

发布评论

评论列表(0)

  1. 暂无评论