简体   繁体   中英

How can I use c# asp.net to get data from url?

I'm trying to get some info I sent by form to angularJS in my c# asp.net backend, and I'm having trouble doing it.

Visual Studio won't let me compile because it says:

Error CS0120: an object reference is required for the nonstatic field, method, or property 'member'

That's is my controller

public class SearchController : ApiController
{
    public string Get()
    {
        string test = HttpContext.Request.QueryString["txt_search"];
        return test;
    }

}

Here's what I got in my angularjs:

$scope.sendForm = function () {
    console.log($scope.model.search);
    $http({
        method: 'GET',
        url: '/api/search?txt_search=' + $scope.model.search
    })
    .then(function () {
        console.log('sucesso a executar o post');
    }, function () {
           console.log('Erro ao executar o post');
       });
};

As suggested in the comments, you should just be able to change your method definition and skip this altogether:

public string Get(string txt_search)
{
    return txt_search;
}

Alternatively, to reference the current request, I believe you need to use the following (note the addition of .Current ):

string test = HttpContext.Current.Request.QueryString["txt_search"];

The reason is that HttpContext defines Request as an instance property. The only public static property is Current , which returns an instance of HttpContext through which you can reach Request .

Welcome to Stack Overflow,

Your Angular code is correct

You need to pass a parameter on server side to collect txt_search value

Here it is:

[HttpGet]
[Route("/api/search")]
public string mySearchMethod(string txt_search)
{
    //something here with txt_search
    return "OK";
}

Both of the above solution will work, but for another approach as you are using asp.net web api and router you can make it as below as well

In your Angular code, simple pass the search as below

```

$scope.sendForm = function () {
    console.log($scope.model.search);
    $http({
        method: 'GET',
        url: '/api/search/'+ $scope.model.search
    })
    .then(function () {
        console.log('sucesso a executar o post');
    }, function () {
           console.log('Erro ao executar o post');
       });
};

```

Notice url: '/api/search/'+ $scope.model.search

and change the Action method as below

```

[HttpGet]
[Route("/api/search/{txt_search}")]
public string mySearchMethod(string txt_search)
{
    //something here with txt_search
    return "OK";
}

```

by doing this you don't have to worry about the name of the parameter txt_search whatever you mention in route [Route("/api/search/{txt_search}")] , you will get the value in same parameter.

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