Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Arabic text via ASP.NET JSON

I want to return Arabic text via asp.net web-method returned as JSON, This is code I'm using:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void getAr()
{
    ResultTemplate resultTemplate = new ResultTemplate();
    resultTemplate.data = "بسم الله";

    JavaScriptSerializer js = new JavaScriptSerializer();
    string retJSON = js.Serialize(resultTemplate);

    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.AddHeader("content-length", retJSON.Length.ToString());
    Context.Response.Flush();
    Context.Response.Write(retJSON);
}

When I run the web-method it keeps loading without any response!

like image 738
Khairy Abd El-Zaher Avatar asked Mar 15 '26 00:03

Khairy Abd El-Zaher


1 Answers

You shouldn't use a WebMethod like this. Change its signature to:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getAr()
{
  string result;
  // fill it ...
  return result;
}

Plus

Response.Flush means send the buffered output immediately. so you should put it at the end.

Context.Response.Write(retJSON);
Context.Response.Flush();

Also content-length is not equal to the string.Length. You should convert it to an array of bytes and then use its length.

byte[] s = Encoding.UTF8.GetBytes(resultString);
response.AddHeader("Content-Length", s.Length.ToString());
response.BinaryWrite(s);
like image 68
VahidN Avatar answered Mar 16 '26 14:03

VahidN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!