Web Service is not returning JSON - asp.net

I know many times this question has been posted over here. But i am not able to find solution for my problem.
I have create one web service and i have set method return type as JSON but method still returns XML.
Here is my method :
[WebMethod(Description = "LoginMethod")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string doLogin(string UserName, string Password)
{
LoginSuccess objSuccess = new LoginSuccess();
UserInfo objInfo = new UserInfo();
objSuccess.success = "true";
objInfo.Token = "token";
objInfo.type = "usertype";
objInfo.username = "username";
objInfo.userid = "userid";
objSuccess.response = objInfo;
clsJSON objJSON = new clsJSON();
loginResponse = objJSON.ToJSON(objSuccess);
return loginResponse;
}
Here is my response :
<string>{"success":"true","response":{"Token":"token","username":"username","userid":"userid","type":"usertype"}}</string>
But i want this as :
{"success":"true","response":{"Token":"token","username":"username","userid":"userid","type":"usertype"}}
I am calling this method from that page which web service giving us to test method. Request method is HttpPost.
Please suggest me for this.

The problem is that you've either not specified or used the wrong accept request header. It should be application/json. Without the relevant javascript code used to fetch data in your question it's not possible to say what exactly you should put where though.

Related

Can I disable model binding and use the raw request body in an action in dotnet core?

I want to setup an endpoint for testing webhooks from third parties. Their documentation is uniformly poor and there is no way ahead of time to tell exactly what I will be getting. What I've done is setup an ApiController that will just take a request and add a row to a table with what they are sending. This lets me at least verify they are calling the webhook, and to see the data so I can program to it.
// ANY api/webook/*
[Route("{*path}")]
public ActionResult Any(string path)
{
string method = Request.Method;
string name = "path";
string apiUrl = Request.Path;
string apiQuery = Request.QueryString.ToString();
string apiHeaders = JsonConvert.SerializeObject(Request.Headers);
string apiBody = null;
using (StreamReader reader = new StreamReader(Request.Body))
{
apiBody = reader.ReadToEnd();
}
Add(method, name, apiUrl, apiQuery, apiHeaders, apiBody);
return new JsonResult(new { }, JsonSettings.Default);
}
This works great, except for this new webhook I am usign that posts as form data so some middleware is reading the body and it ends up null in my code. Is there any way to disable the model processing so I can get at the request body?
You could actually use model binding to your advantage and skip all that stream reading, using the FromBody attribute. Try this:
[Route("{*path}")]
[HttpPost]
public ActionResult Any(string path, [FromBody] string apiBody)

How do I pass JObject from Fiddler to Web Api?

I have function using JObject as parameter. Like this:
public void AddDevice(JObject jsonData)
{
dynamic json = jsonData;
JObject juser = json.User;
string login = json.UserLogin;
var user = juser.ToObject<User>();
//some operations on user and login
}
The question is: how do I pass do web api test user and login from Fiddler? Method is HttpPost type of course.
#edit
Im not asking how do I use Fiddler, I am asking how do I write correctly Body Request for JObject.

Restsharp return null when Response have location header only, no body

i am using RestSharp to consume the CapsuleCRM API.
When you POST to create an entity, the API does not return anything in the body of the response, only a location header to the newly created row.
Like so:
http://developer.capsulecrm.com/v1/writing/
HTTP/1.1 201 Created
Location: https://sample.capsulecrm.com/api/party/1000
So, if RestSharp is to be able to return an object, it must follow that location header url, and retrieve the new object from there, but this does not seem to be happening.
This questions is similar to a different question, but not a duplicate:
RestSharp returns null value when response header has location field
Update:
I have posted a hacky solution I came up with as an answer, but is there really no way for RestSharp to handle this by default?
I was able to make this work by making a tweaked version of the
public T Execute<T>(RestRequest request) where T : new()
method, but it really feels like there should be a better solution to this.
Source code at:
https://github.com/bjovas/CapsuleDotNet/blob/master/src/CapsuleDotNetWrapper/CapsuleApi.cs
public T CreateExecute<T>(RestRequest request) where T : new()
{
var client = new RestClient();
client.BaseUrl = BaseUrl;
client.Authenticator = new HttpBasicAuthenticator(_authtoken, "x");
var response = client.Execute<T>(request);
string locationUrl = (string)response.Headers.Where(h => h.Type == ParameterType.HttpHeader && h.Name == "Location").SingleOrDefault().Value;
int id;
if (int.TryParse(locationUrl.Remove(0, string.Format("{0}{1}", client.BaseUrl, request.Resource).Length), out id))
{
var secondRequest = new RestRequest();
secondRequest.Resource = locationUrl.Remove(0, string.Format("{0}", client.BaseUrl).Length);
secondRequest.RootElement = request.RootElement;
return Execute<T>(secondRequest);
}
else
throw new ApplicationException("Could not get ID of newly created row");
}

Dotnetopenauth, retrieve email from facebook scope

Have a question I surpsisingly couldnt find an answer to when searching around.
If I request a users email from facebook like:
var scope = new List<string>();
scope.Add("email");
FbClient.RequestUserAuthorization(scope);
How do I retrieve it? I couldnt find a clear option for this in the FacebookGraph.
Near as I can tell, the FacebookGraph object that is in the examples from DotNetOpenAuth does not support changing the fields that you are receiving. However, since WebRequest that it is prompting is returning a JSON string, you can parse it yourself (or use another JSON parser). That's exactly what I did, using the NewtonSoft.Json.dll:
//as part of the uri for the webrequest, include all the fields you want to use
var request = WebRequest.Create("https://graph.facebook.com/me?fields=email,name&access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, true);
string MyStr = streamReader.ReadToEnd();
JObject userInfo = JObject.Parse(MyStr);
//now you can access elements via:
// (string)userInfo["name"], userInfo["email"], userInfo["id"], etc.
}
}
Note that you specify what fields you want sent back as part of the WebRequest URI. The fields that are available can be found at https://developers.facebook.com/docs/reference/api/user/
Using DNOA This answer did it for me.
Just added the following:
var scope = new List<string>();
scope.Add("email");
client.RequestUserAuthorization(scope);
and the following to the facebook graph.
[DataMember(Name = "email")]
public string EMail { get; set; }
What you wrote above appears to be requsting authorization from the user to allow your app to get email back when you query the user's object. To query the user's object you do an HTTP Get on https://graph.facebook.com/me. Try it out in the Graph API explorer tool at https://developers.facebook.com/tools/explorer

ASP.NET WebMethod Returns JSON wrapped in quotes

I have an asp.net page with a WebMethod on it to pass JSON back to my javascript.
Bellow is the web method:
[WebMethod]
public static string getData(Dictionary<string, string> d) {
string response = "{ \"firstname\": \"John\", \"lastname\": \"Smith\" }";
return response;
}
When this is returned to the client it is formatted as follows:
{ \"d\": \"{ \"firstname\": \"John\", \"lastname\": \"Smith\" }\" }
The problem is the double quotes wrapping everything under 'd'. Is there something I've missed in the web method or some other means of returning the data without the quotes? I don't really want to be stripping it out on the client everytime. Also I've seen other articles where this doesn't happen.
Any help would be appreciated thanks.
I assume that you want to return the JSON representation of the object
{
firstname:"John",
lastname:"Smith"
}
but your method signature is returning a string. The ASP.Net framework serialisation is correctly serialising the string response. Put another way, if your function was
string response = "foo";
return response;
You would not be surprised if the output was
{"d":{"foo"}}
It just happens that response has double quotes that need to be escaped.
You obviously just want to get at the object. You have 2 options: -
1) use eval in your javascript to turn the string into an object e.g.
function onSuccessCallback(retval) {
var obj = eval(retval.d);
}`
2) or (and this is my prefered solution) have your method return an actual object and let the JSON serialisationof the framework do the heavy lifting for you
[WebMethod]
public static object getData(Dictionary<string, string> d) {
var response = new { firstname = "John", lastname="Smith" };
return response;
}
You will see that this generates the response that you probably originally expected (e.g.
{"d":{"firstname":"John", "lastname":"Smith"}}
Actually this entire issue exists because you're trying to out-think ASP.Net web services. You need to setup a class for your data to be returned and use that class (or List(of YourClass)) to queue up results and return them.
A great article explaining all this (a very common pitfall) is: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
I had a similar issue with my code. I was trying to return an XmlDocument as JSON to a calling script but returning XmlDocument from the WebService returned an empty set of arrays (as XmlDocument is NOT serializable!).
If i set the ScriptService with the attribute ResponseFormat.JSON then my JSON was double-escaped.
The way to out-fox ASP.NET is to tell ASP.NET that you're returning XML and then it won't double-escape your JSON ;-)
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public String MyJSONWebService(String sParam1, String sParam2, String sParam3)
{
... do stuff.....
XmlDocument oXMLDocument = new XmlDocument();
oXMLDocument.LoadXml(sXML);
sJSON = JsonConvert.SerializeXmlNode(oXMLDocument.SelectSingleNode("autnresponse"));
return sJSON;
}
I know it's a hack but .....

Resources