Receive and Send JSON C #

2

In a local application "WindowsForm" in C #, I need to send and receive data via JSON to a PHP page, is there any predefined function for this?

    
asked by anonymous 21.06.2016 / 20:44

1 answer

0

Practically you need some declarations in order for your WebServices to work.

  

[ScriptMethod (ResponseFormat = ResponseFormat.Json)]

Specifies the HTTP verb that is used to call a method and the format of the response. This class can not be inherited. Details

  

JavaScriptSerializer

Json.NET should be used for serialization and deserialization. Provides serialization and deserialization functionality for applications that use AJAX. Details

  

writeJsonData

And a method that assembles your JSON (response), as an example: writeJsonData

See details of a XML Web Services from Windows Forms and Link to a Web Service using the Windows Forms BindingSource

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod()]
public void DadosUsuario(String IdUsuario, String Chave)
{
    using (var DBCtx = new WdbContext())
    {
        try
        {
            var Usuario = DBCtx.tb_Usuarios.FirstOrDefault();
            if (Usuario != null)
                RetornarJson(DBCtx, Usuario);  
        }
        catch (Exception exc)
        {
        }
    }
}

private void RetornarJson(WdbContext DBCtx, tb_Usuarios Usu)
{
    string RespJson = String.Empty;

    JavaScriptSerializer js = new JavaScriptSerializer();
    RespJson = js.Serialize(Usu);
    writeJsonData(RespJson);            
}

protected void writeJsonData(string s)
{
    HttpContext context = this.Context;
    HttpResponse response = context.Response;
    context.Response.ContentType = "application/json";
    byte[] b = response.ContentEncoding.GetBytes(s);
    response.AddHeader("Content-Length", b.Length.ToString());
    response.BinaryWrite(b);
    try
    {
        this.Context.Response.Flush();
        this.Context.Response.Close();
    }
    catch (Exception) { }
}
    
21.06.2016 / 21:16