Send parameters to Restfull services [closed]

0

I have a mvc web application and I have an action that should pass a parameter to a REST service. How do I pass a parameter to a REST service. I know I will have to implement an HttpPost, but how? Anyone know of a tutor who can help us?

EDIT1

The following. Imagine a parent company with 7 stores. Each store with its team of vendors. A customer arrives at this store and makes a purchase. It is very common to sell more than R $ 5,000.00. In this sale there are several items. Well, let's say that a given customer bought inputs, vaccines and etc and gave there 120,000.00. As he has the money, he asks for a long term (until the crop, maybe) a discount. It turns out that this discount is beyond the ability of the seller to grant, so he starta the guy right above it, which is usually in the matrix. How does he do that? Changing a flag in the BD (FLAG_LIBERACAO) from 1 to 0. That is when the system will act. This change the developers of the company will make (system done in Clarion / InterDev). What happens is, when the customer requests the discount, the seller clicks on a button that changes the Flag and already sends to the service (here enters my system) the Request (I put OK / Deny) but it can be anything. Then the service picks up this newly arrived information and launches a Push Notification (PN). And each manager / director receives and does what he / she has to do. There is a rule for each to receive, but that is another thing and I am already trapping it. I hope to be clear, but if there is still doubt, I am here to respond.

EDIT2

I set up my API like this:

public class GetValueLiberacao
    {
        [Route("api/postvalueliberacao/{value}")]
        [AcceptVerbs("Post")]
        public HttpResponseMessage PostValueLiberacao([FromBody] string value)
        {
            try
            {
                if (value == "Ok")
                {
                    Task t = new Task(async () =>
                    {
                        await SenderMessage();
                    });
                    t.Start();
                }

                var response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent("OK")
                };

                return response;
            }
            catch(Exception ex)
            {
                var response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent("Falha \n" + ex.Message)
                };
                return response;
            }
        }

        public static async Task<IFCMResponse> SenderMessage()
        {
            FCMClient client = new FCMClient("AAAA0myCZjE:APA91bETPO0K3EtgBhHz_gMXDtBTiQrCsFaOW8wmFxbk5XvYhxTRIW9ZQR_mxNU8ThWe0d0A40JzG-Up_P2qyCw9hf6DrrRJfpynRIpnv_8FjIk3BsElnBuRenOi0h2r_h7Bv_"); //as derived from https://console.firebase.google.com/project/
            var message = new Message()
            {
                To = "APA91bGmgZnr2YMolubwS7c_e6AAkbVj6ga83lSHLo31FRUoom3iuS73PR1Bo6-iJEZWA88Xom7SWMrBK7edS6xVoe0kHdoIEowye4dsKXdtHdjd60_QEYcBkIi9QLyP7ZX6qdfdj", //topic example /topics/all
                Notification = new AndroidNotification()
                {
                    Body = "Solicitação de Novo Desconto",
                    Title = "Desconto",
                }
            };
            //CrossBadge.Current.SetBadge(1, "Teste");
            var result = await client.SendMessageAsync(message);
            return result;
        }
    }

If I receive OK in the parameter, I then trigger Push Notification. Now I'm working on consuming and sending the parameter, from another application. The doubt now would be the controller, as it would be, since it is for her that the program will send the data. I have not set it yet. I just did this method and I need to set up the controller that will make it happen. Will I need EnableCors ?

EDIT3 I made my controller like this:

[RoutePrefix("api/postvalueliberacao")]
    public class GetLiberaItensController : ApiController
    {
        AutorizadorContext contexto = new AutorizadorContext();
        GetValueLiberacao libitens = new GetValueLiberacao();

        [Route("{value}")]
        [AcceptVerbs("Post")]
        public HttpResponseMessage GetLiberaItens(string value)
        {
            return libitens.PostValueLiberacao(value);
        }
    }

I'll start to attest. First in Postman and then in my application.

    
asked by anonymous 18.10.2017 / 19:50

1 answer

2

I use the following function:

    public static string HttpPost(string url, string postData, string token)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        byte[] data = Encoding.ASCII.GetBytes(postData);
        request.Headers["api-token"] = token;
        request.Method = "POST";
        request.Accept = "application/json";
        request.ContentType = "application/json; charset=utf-8";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        return responseString;
    }

Just inform the url, the data that will be sent, in case you are sending a json, and the token that should go in the header. Remembering that this is specific to each api, and you have to refer to it in the documentation.

Edit:

Consider the following code for the API:

    [ApplyModelValidation]
    public IHttpActionResult Post([FromBody]string valor)
    {
        try
        {
             //faz qualquer processo...               
             return Ok("retorno: "+ valor);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

You would consume it like this:

POST method:

    public static string HttpPost(string url, string postData)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        byte[] data = Encoding.ASCII.GetBytes(postData);
        request.Method = "POST";
        request.Accept = "text/plain";
        request.ContentType = "text/plain; charset=utf-8";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        return responseString;
    }

Consuming:

public void Consumir()
{
    string retorno = HttPost("http://minhaapi.com.br/api/controller/","esse texto q eu estou enviando");

    //resultado: "retorno: esse texto q eu estou enviando";
}

I hope it helps, and obviously did not test, may have some error.

    
18.10.2017 / 19:56