I need to create a WebMethod that returns my member database values on JSON. I try something like that but it actually failed.
[WebMethod(EnableSession = false)]
public static UYELER handleAjaxRequest(string mailX, string passwordX)
{
DataSet dsX = ReadSql("select top 3 * from fuyeler ");
for (int i = 0; i < dsX.Tables[0].Rows.Count; i++)
{
mailX = dsX.Tables[0].Rows[i]["stMail"].ToString();
passwordX = dsX.Tables[0].Rows[i]["stPass"].ToString();
}
return new UYELER
{
mail = mailX,
password = passwordX,
};
}
public class UYELER
{
public int ID { get; set; }
public string mail { get; set; }
public string password { get; set; }
}
Readsql is my quick sql connection class.
You can return Json from an Asp.Net method by clearing the normal output in Page_Load and returning your own output. See this StackOverflow answer...
To convert a C# object to JSON you can use a library such as Json.NET.
Method 1:
Add this to your Application_Start in Global.asax page:
protected void Application_Start()
{
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
//....
}
Method 2
You can alse decorate your method with ResponseFormat set JSON
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = false)]
public static UYELER handleAjaxRequest(string mailX, string passwordX)
{
DataSet dsX = ReadSql("select top 3 * from fuyeler ");
for (int i = 0; i < dsX.Tables[0].Rows.Count; i++)
{
mailX = dsX.Tables[0].Rows[i]["stMail"].ToString();
passwordX = dsX.Tables[0].Rows[i]["stPass"].ToString();
}
return new UYELER
{
mail = mailX,
password = passwordX,
};
}
Related
We are using 3rd party api kraken.io to optimize our images.
The results of optimized image is posted in a Webhook.
In their api document it states: After the optimization is over Kraken will POST a message to the callback_url specified in your request in a JSON format application/json.
I am using ngrok to allow remote webhooks to send data to my development machine, using this article.
Results posted to the Callback URL:
HTTP/1.1 200 OK
{
"id": "18fede37617a787649c3f60b9f1f280d",
"success": true,
"file_name": "header.jpg",
"original_size": 324520,
"kraked_size": 165358,
"saved_bytes": 159162,
"kraked_url": "http://dl.kraken.io/18/fe/de/37617a787649c3f60b9f1f280d/header.jpg"
}
Class to Map
public class KrakenOptimizedResults
{
public string id { get; set; }
public bool success { get; set; }
public string file_name { get; set; }
public int original_size { get; set; }
public int kraked_size { get; set; }
public int saved_bytes { get; set; }
public string kraked_url { get; set; }
}
Action Method
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string jsonString = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
KrakenOptimizedResults obj = new JavaScriptSerializer().Deserialize<KrakenOptimizedResults>
(jsonString);
return Json(obj);
}
But When I debug the received jsonString in Html Visualizer it looks like key and value pairs instead of Json format.
Received Results not Json Formatted:
file_name=header.jpeg&original_size=118066&kraked_size=102459&saved_bytes=15607
I guess the received data content-type: is application/x-www-form-urlencoded.
Why i am receiving key and value pairs instead of Json format ? how can I deserialize Json data in asp.net mvc ?
Co-founder of https://kraken.io here.
There is a glaring omission in our documentation which I will fix today. To get JSON back, you need to set a "json": true flag in the request. Omitting that flag or setting "json": false will return URLEncoded. Example cURL request:
curl http://api.kraken.io/v1/upload -X POST --form data='{"auth":{"api_key":"YOUR_KEY", "api_secret":"YOUR_SECRET"}, "wait": true, "lossy": true, "callback_url": "http://requestb.in/wbhi63wb", "json": true}' --form upload=#test.jpg
Sorry for the inconvenience :-(
I was able to convert Query String Key and Value pairs to Json Format using this and this post ,there is some delay to convert form Dictionary to Json, so If there is better answers, then do post and advice, below is my solution.
Action Method
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string data = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
var dict = HttpUtility.ParseQueryString(data);
var json = new JavaScriptSerializer().Serialize(dict.AllKeys.ToDictionary(k => k, k =>
dict[k]));
KrakenOptimizedResults obj = new JavaScriptSerializer().Deserialize<KrakenOptimizedResults>
(json);
return Json(obj);
}
Recieving JSON formated optimized results from kraken API.
As mentioned by #karim79, To get JSON back, you need to set a "json": true flag in the request.
As Kraken .Net/C# SDK didn't have option to set "json": true, so i have to extend their base class.
Extended Base Class:
public class OptimizeRequestBaseExtended : OptimizeRequestBase,
IOptimizeUploadRequest, IRequest
{
public OptimizeRequestBaseExtended(Uri callbackUrl)
{
CallbackUrl = callbackUrl;
}
[JsonProperty("callback_url")]
public Uri CallbackUrl { get; set; }
[JsonProperty("json")]
public bool JsonFormat { get; set; }
}
Request Kraken API:
var callbackUrl = new Uri("http://localhost:0000/Home/OptimizedWebHook");
OptimizeRequestBaseExtended settings = new OptimizeRequestBaseExtended(callbackUrl);
settings.Lossy = true;
settings.JsonFormat = true;
var response = client.Optimize(image: image, filename: filename, optimizeRequest: settings);
Action Method
[HttpPost]
public ActionResult OptimizedWebHook()
{
Request.InputStream.Position = 0;
string jsonString = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
KrakenOptimizedResults obj = JsonConvert.DeserializeObject<KrakenOptimizedResults>
(jsonString);
return Json(obj);
}
Step 1:
Create an aspx page. This page must be able to accept HTTP POST request.
Step 2:
Add this code to get HTTP POST data.File: default.aspx.cs
File: default.aspx.cs
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(#"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(json.ToString() + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Step 3:
Create webhook. This code can be linked to a button on click event.File:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
List<string> events = new List<string>();
events.Add("Update");
string postback = list.CreateWebhook(events, "URL", "json");
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(#"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(postback + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Step 4:
Activate webhook. Copy that webhook id from the text file and past it to the code below.
File:default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
list.ActivateWebhook("webhook id");
Step 5:
Test weebhook.File: default.aspx.cs
AuthenticationDetails auth = new ApiKeyAuthenticationDetails("your api key");
string listID = "";
listID = "your list id";
List list = new List(auth, listID);
string postback = list.TestWebhook("webhook id").ToString();
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
ostrm = new FileStream(#"C:\logfile4webhook.txt", FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(DateTime.Now + " ");
Console.WriteLine(postback + " ");
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Step 6:
Deserialize body of JSON object. We need to create class structure based on JSON data. I put sample json here and it created required classes
public class CustomField
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Event
{
public List<CustomField> CustomFields { get; set; }
public string Date { get; set; }
public string EmailAddress { get; set; }
public string Name { get; set; }
public string SignupIPAddress { get; set; }
public string Type { get; set; }
}
public class RootObject
{
public List<Event> Events { get; set; }
public string ListID { get; set; }
}
Once you have created your class, append the code from step 2 after
var json = reader.ReadToEnd();
to deserialize and parse json.
RootObject myClass = JsonConvert.DeserializeObject(json);
if (myClass != null)
{
List<Event> t = myClass.Events;
string old_email = "", new_email = "";
old_email = t[0].OldEmailAddress;
new_email = t[0].EmailAddress;
//now you can do your logic with old_email and new_email
}
I am having some problems getting my ASP.NET MVC application to parse my model, i simply just get "null".
This is my ASP.NET MVC action
public AdobeReturnSet<UserModel> Post([FromBody]UserModel model)
I have also tried without the [FromBody], that did not help.
This is my model
public class UserModel
{
public int AdobeId { get; set; }
[Required]
[StringLength(500)]
public string FristName { get; set; }
[Required]
[StringLength(500)]
public string LastName { get; set; }
[Required]
[StringLength(250)]
[EmailAddress]
public string Email { get; set; }
[Required]
public string OrganizationIdentification { get; set; }
public string Organization { get; set; }
public string OrganizationFull { get; set; }
}
And this is how i send the request
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Accept] = "application/json";
wc.Headers[HttpRequestHeader.AcceptCharset] = "utf-8";
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
result = wc.UploadString(url, "POST", data);
}
The url is correct as the correct action is reached and this is the value of data:
{"AdobeId":0,"FristName":"Kasper Rune","LastName":"Søgaard","Email":"krus#arcanic.dk","OrganizationIdentification":null,"Organization":null,"OrganizationFull":null}
But when the request reaches my action is the model simply null.
It is a ApiController if that changes anything.
Looks like an encoding problem. Try using the UploadData method instead and use UTF-8 encoding:
using (var wc = new WebClient())
{
var data = Encoding.UTF8.GetBytes(#"{""AdobeId"":0,""FristName"":""Kasper Rune"",""LastName"":""Søgaard"",""Email"":""krus#arcanic.dk"",""OrganizationIdentification"":null,""Organization"":null,""OrganizationFull"":null}");
wc.Headers[HttpRequestHeader.Accept] = "application/json";
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
byte[] result = wc.UploadData(url, "POST", data);
string json = Encoding.UTF8.GetString(result);
}
Alternatively you could use the new HttpClient:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.ConnectionClose = true;
var value = new
{
AdobeId = 0,
FristName = "Kasper Rune",
LastName = "Søgaard",
Email = "krus#arcanic.dk",
};
var result = client.PostAsJsonAsync(url, value).Result;
if (result.IsSuccessStatusCode)
{
string json = result.Content.ReadAsStringAsync().Result;
}
}
Also you might have a typo at FristName which should probably be FirstName.
I am the new one with the using of web service with ASP.net MVC 3.0. Now I have another member in my team, they develop web service and then they passed the URL to me http://localhost:55274/iServices/Generics/Setting.svc/GetSetting/ , then I received the JSON data
{"ID":1,"MailAccount":"blahbla.com","MailPassword":"password","SMTP":"smtp.test.com","SMTPPort":500,"SSL":false}
Now I am trying to get that JSON to use in the class of my ASP.net MVC 3 to provide the mail system setting. I created two class :
public class iceEmailObject
{
public int ID { set; get; }
public String SMTP { set; get; }
public int SMTPPort { set; get; }
public String MailAccount { set; get; }
public String MailPassword { set; get; }
public bool SSL { set; get; }
}
The second class is to handle send mail :
public class EASEmail : ItemEntityDataContext
{
public bool SendMail(string ReplyTo, string SendTo, string Title, string Body, string From, string AttachmentPath, bool isHtml = false)
{
try
{
SmtpMail oMail = new SmtpMail("blah blah blah");
SmtpClient oSmtp = new EASendMail.SmtpClient();
String fff = From;
if (From == "") fff = ReplyTo;
MailAddress ma = new EASendMail.MailAddress(fff, "");
if (From == "")
{
oMail.ReplyTo = ReplyTo;
oMail.Headers.Add("Reply-To", ReplyTo);
}
oMail.From = ma;
oMail.To = SendTo;
oMail.Subject = Title;
oMail.Priority = MailPriority.High;
if (!isHtml)
oMail.TextBody = Body;
else
oMail.HtmlBody = Body;
iceEmailObject mail = new iceEmailObject();
mail.ID = blahblah; //data from web service here
mail.MailAccount = ""; //data from web service here
return true;
}
catch (Exception ex)
{
return false;
}
}
}
I want to get the JSON to initial the object of the first class such as mail.ID = ....
Could any one tell me how could I do that? Thanks.
Try this
JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
iceEmailObject mail = js.Deserialize<iceEmailObject>(json);
where json is your JSON string, and mail is the resulting object
I am not getting any root value of the Json Format.
I am getting the response as follows:
[{"Username":"demo","UserID":8,"Password":"demo","EmaiID":"demo#gmail.com"}]
I would like to have the format as follows
{UserList: [[{"Username":"demo","UserID":8,"Password":"demo","EmaiID":"demo#gmail.com"}]}
Service Declaration :
public interface IDemo
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,ResponseFormat =
WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/Validate", Method = "POST")]
Stream ValidateUser(Login obj);
}
[DataContract]
public class Login
{
public Login()
{
}
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
}
Service Definition :
public class Demo: IDemo
{
string Json = string.Empty;
JavaScriptSerializer obj1 = new JavaScriptSerializer();
public Stream ValidateUser(Login obj)
{
UserList objUserList = new UserList();
Users objUser = new Users();
objUser.Username = obj.Username;
objUser.Password = obj.Password;
objUserList = LoginDataService.ValidateUser(objUser.Username,objUser.Password) ;
if (objUserList.Count > 0)
{
Json = obj1.Serialize(objUserList);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/json; charset=utf-8";
}
else
{
UserError objError = new UserError();
objError.ErrMsg = "LoginFailed";objError.Username = objUser.Username ;
Json = obj1.Serialize(objError);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/json; charset=utf-8";
}
return new MemoryStream(Encoding.UTF8.GetBytes(Json));
}
}
Can anyone help me to get the result with root element and let me know what kind of mistake i have done.
Thanks & Regards,
Vijay
You are getting the format like that since you are serializing a collection into JSON. You can return a class that wraps the list inside as a property then you will get what you desire.
For ex. you can create a class like this
public class UserListResponse
{
public UserList UserList{get; set;}
}
Now you get the JSON as what you expected, like
{UserList:[..]}
I don't understand why you are returning a Stream and doing yourself all the serialization framework, basically this all done by the framework. All you have to do is return the wrapper class UserListResponse from the service method.
public class Demo: IDemo
{
public UserListResponse ValidateUser(Login obj)
{
...
return new UserListResponse{ UserList = objUserList};
}
}
The WCF will take care of returning the structure into JSON or XML and you don't need to worry about that.
While the above solution perfectly works you can also try using paramter BodyStyle=WebMessageBodyStyle.WrappedResponse of WebInvoke attribute on your method.
This wraps the values in type name.
This code was working just fine before i moved to MVC3 ...
[HttpPost]
[ActionName("GetCommentListForServiceCall")]
[UrlRoute(Path = "mobile/servicecalls/{id}/comments", Order=1)]
[UrlRouteParameterConstraint(Name = "id", Regex = #"\d+")]
[OutputCache(CacheProfile = "MobileCacheProfile")]
[JsonFilter(JsonDataType = typeof(ServiceCallCommentNewDTO), Param = "comment")]
public JsonNetResult CreateCommentForServiceCall(int id, ServiceCallCommentNewDTO comment)
{
ServiceCallComment entity = coreSvc.SaveServiceCallComment(id, 0, comment.CategoryId, comment.Comment);
SetResponseCode(HttpStatusCode.Created);
SetContentLocation(string.Format("mobile/servicecalls/{0}/comments/{1}", id.ToString(), entity.Id.ToString()));
return new JsonNetResult(entity); ;
}
here is the JSonFilterAttribute code
public class JsonFilterAttribute : ActionFilterAttribute
{
public string Param { get; set; }
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
{
string inputContent;
using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
inputContent = sr.ReadToEnd();
}
var result = JsonConvert.DeserializeObject(inputContent, JsonDataType, new JsonSerializerSettings{TypeNameHandling = TypeNameHandling.All});
filterContext.ActionParameters[Param] = result;
}
}
}
Now The JsonFilter doesn't get the object anymore. It always return null ?
Is there something i have to do in MVC3 ?
You no longer need this attribute as ASP.NET MVC 3 has this functionality built-in.