I created a Rest Webservice with ASP.NET MVC 4 and in my Webservice I'm calling a delegater which is called MessageInformer.
public MessageRepository repository = new MessageRepository();
public HttpResponseMessage PostMessage([FromBody]CoreMessage item)
{
bool status = repository.TransmitMessage(item);
if (status == true)
{
return Request.CreateResponse<bool>(HttpStatusCode.OK, status);
}
else
{
return Request.CreateResponse<bool>(HttpStatusCode.BadRequest, status);
}
}
public class MessageRepository : IMessageRepository
{
public static MessageInformer Informer;
public void SetDelegater(MessageInformer i)
{
Informer = i;
}
public bool TransmitMessage(CoreMessage item)
{
Informer(item);
return true;
}
}
When I start running the program I set a value to the delegater
MessageRepository mr = new MessageRepository();
mr.SetDelegater(informer);
that it should call the function New_MessageReceived and in the debug mode I see that the delegater has the right value after declaring it but when I call the Rest client after starting the program and it's comming to the function TransmitMessage(CoreMessage item) the delegater Informer is null although I assigned a value to it before. I set some breakpoints and it's never entering the function or the delegater between the starting and the web request so I don't have any idea why my delegater is null.
Rest client
try
{
url = "http://localhost:5089/api/message";
method = "POST";
string messageString = JsonConvert.SerializeObject(message);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json; chatset=utf-8";
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
writer.Write(messageString);
}
var response = request.GetResponse() as HttpWebResponse;
if (request.HaveResponse == true && response == null)
{
String msg = "response was not returned or is null";
throw new WebException(msg);
}
if (response.StatusCode != HttpStatusCode.OK)
{
String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
throw new WebException(msg);
}
// check response headers for the content type
string contentType = response.GetResponseHeader("Content-Type");
// get the response content
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = reader.ReadToEnd();
reader.Close();
Console.WriteLine("Received " + messageString);
}
catch (Exception ex)
{
reponseAsString += "ERROR: " + ex.Message;
}
this
public MessageRepository repository = new MessageRepository();
not that
MessageRepository mr = new MessageRepository();
mr.SetDelegater(informer);
You should make sure repository is initialized properly (did you forget to assign mr to <object>.repository?).
Related
I am trying to output a small popup-like window to the user saying either the restful command was successfully accepted or not (and display the Http Code).
I am really looking for direction on how to do this properly in ASP.NET MVC.
Controller Function
public void ExportJira()
{
string postUrl = "https://somewebsite.org/rest/api/2/issue";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//Using Service Account for Demo Jira Instance
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("FakeAccount:fakePw"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = #"{""fields"":{""project"":{""key"": ""SDR""},""summary"": ""This is SDR Web App"",""issuetype"" : {""id"":""3""}}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine("Errorcode: {0}", (int)httpResponse.StatusCode);
System.Diagnostics.Debug.WriteLine("Support Headers: \n" + httpResponse.SupportsHeaders + "\n");
System.Diagnostics.Debug.WriteLine("Headers: \n" + httpResponse.Headers + "\n");
TempData["msg"] = "<script>alert('Success!" + (int)httpResponse.StatusCode + "');</script>";
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
httpResponse = (HttpWebResponse)e.Response;
TempData["msg"] = "<script>alert('Failed!" + (int)httpResponse.StatusCode + "');</script>";
}
else
{
TempData["msg"] = "<script>alert('Failed!" + (int)httpResponse.StatusCode + "');</script>";
}
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
View Code
#Html.ActionLink("Export to Jira", "ExportJira", null, new { id = "myLink" })
#Html.Raw(TempData["msg"])
Every get or post controller function should return a view model, that can be used by the view to display whatever is relevant. Rather than using TempData, do something like this
class ExportJiraViewModel
{
public string Message {get;set;}
}
public IActionResult ExportJira()
{
var vm = new ExportJiraViewModel();
// fill out vm where appropriate
return View(vm);
}
I have an OpenIdConnect Server I'm connecting to an I would like to forward token data the first time logging in to be stored on the server. Currently I'm doing this to forward the access token
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
I want to send the Profile Data as well but I don't know the proper header.
How can I do something like this:
xhr.setRequestHeader("Authorization-Profile", "Bearer " + user.profile);
Does anyone know the proper header so I can add these claims to the access token.
Here is an example of what we did in one of our project:
Created a common API response class as below:
public class ApiCommonResponse
{
public object Object { get; set; }
public int httpStatus { get; set; }
public string httpErrorMessage { get; set; }
}
And a generic method to call GET and POST API endpoints. This method will map the response to the supplied data model and will return you the object.
public static ApiCommonResponse GetApiData<T>(string token, T dataModel, string apiEndPoint = null)
{
var responseText = "";
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint != null)
{
var request = (HttpWebRequest)WebRequest.Create(apiEndPoint);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("X-Api-Version", "");
try
{
var httpResponse = (HttpWebResponse)request.GetResponse();
var stream = httpResponse.GetResponseStream();
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
responseText = streamReader.ReadToEnd();
}
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
}
var jsonSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };
apiCommonResponse.Object = JsonConvert.DeserializeObject<T>(responseText, jsonSettings);
apiCommonResponse.httpStatus = 0;
return apiCommonResponse;
}
public static ApiCommonResponse PostApiData<T>(string username, string token, T dataModel, string apiEndPoint = null)
{
var apiCommonResponse = new ApiCommonResponse();
if (apiEndPoint == null) return null;
var webRequest = WebRequest.Create(apiEndPoint);
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-Api-Version", "");
using (var requeststreams = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(requeststreams))
{
sw.Write(JsonConvert.SerializeObject(dataModel));
}
}
try
{
var httpStatus = (((HttpWebResponse)webRequest.GetResponse()).StatusCode);
var httpMessage = (((HttpWebResponse)webRequest.GetResponse()).StatusDescription);
using (var s = webRequest.GetResponse().GetResponseStream())
{
if (s == null) return null;
using (var sr = new StreamReader(s))
{
var responseObj = sr.ReadToEnd();
if (!string.IsNullOrEmpty(responseObj))
{
apiCommonResponse = JsonConvert.DeserializeObject<ApiCommonResponse>(responseObj);
}
}
apiCommonResponse.httpStatus = (int)httpStatus;
apiCommonResponse.httpErrorMessage = httpMessage;
apiCommonResponse.Object = apiCommonResponse.Object;
}
}
catch (WebException we)
{
var stream = we.Response.GetResponseStream();
if (stream != null)
{
var resp = new StreamReader(stream).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
throw new Exception(obj.ToString());
}
}
return apiCommonResponse;
}
We use Windows Azure website management library and create a web app programmatically by using C# code but we cannot create a virtual directory inside a web app. please help me how to create virtual directory inside a web app programmatically
My Code here
var websiteManagementClient =
CloudContext.Clients.CreateWebSiteManagementClient(Credentials);
var webSpaces = websiteManagementClient.WebSpaces.List();
var webSpace = webSpaces.FirstOrDefault(x => x.GeoRegion == "South Central US");
if (webSpace == null)
{
throw new Exception(string.Format("No webspace for region {0} found", "South Central US"));
}
var webHostingPlans = websiteManagementClient.WebHostingPlans.List(webSpace.Name);
var webHostingPlan = webHostingPlans.FirstOrDefault();
if (webHostingPlan == null)
{
throw new Exception(string.Format("No webhostingplan found"));
}
try
{
var website = websiteManagementClient.WebSites.Get(webSpace.Name, "MyAzureTestSite", null);
if (website != null)
{
throw new Exception(string.Format("The website {0} already exists", ""));
}
}
catch (Exception)
{
}
var websiteCreateParams = new WebSiteCreateParameters();
websiteCreateParams.Name = "MyAzureTestSite";
websiteCreateParams.ServerFarm = webHostingPlan.Name;
websiteManagementClient.WebSites.Create(webSpace.Name, websiteCreateParams);
At first I tried to create virtual directory with the help of Azure SDK but was not successful. Finally, I used http request to create it.
If you can use this method, you can check it out on my blog.
http://kapiltak.blogspot.in/2015/10/how-to-create-virtual-application-in.html
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading;
namespace ConsoleApplication1
{
public class Azure
{
private string loginpath = "https://login.windows.net/{0}";
private string apiEndpoint = "https://management.azure.com/";
//Fill these up
private string webSiteName = "{your webSiteName}";
private string webSpaceName = "Default-Web-SoutheastAsia"; //Insert your webSpaceName here
private string tenantId = "{your tenantId}";
private string clientId = "{your client Id}";
private string subscriptionId = "{your subscription Id}";
//Not needed to set in console app because a function is called to get the token
//string token = "";
public void CreateVD(string name)
{
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(#"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
request.Headers.Add("x-ms-version", "2013-03-01");
request.ContentType = "application/json";
var token = GetAuthorizationHeader();
request.Headers.Add("Authorization", "Bearer" + " " + token);
System.Net.WebResponse response = request.GetResponse();
string data = "";
using (System.IO.Stream stream = response.GetResponseStream())
{
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
data = sr.ReadToEnd();
sr.Close();
stream.Close();
Console.WriteLine("data found");
}
if (data == "")
{
Console.WriteLine("Error in collecting data");
return;
}
string path = name, directory = name;
data = data.Replace("virtualApplications\":[", "virtualApplications\":[{\"virtualPath\":\"/" + path + "\",\"physicalPath\":\"site\\\\wwwroot\\\\" + directory + "\",\"preloadEnabled\":false,\"virtualDirectories\":null},");
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(#"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
request.Headers.Add("x-ms-version", "2013-03-01");
request.ContentType = "application/json";
request.AllowWriteStreamBuffering = false;
request.Accept = "Accept=application/json";
request.SendChunked = false;
request.Headers.Add("Authorization", "Bearer" + " " + token);
request.ContentLength = data.Length;
request.Method = "PUT";
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
response = request.GetResponse();
using (System.IO.Stream stream = response.GetResponseStream())
{
data = (new System.IO.StreamReader(stream)).ReadToEnd();
Console.WriteLine("DONE");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
private string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext(string.Format(loginpath, tenantId));
var thread = new Thread(() =>
{
result = context.AcquireToken(apiEndpoint, clientId, new Uri(redirectUri));
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
}
This code can be used to create virtual directory from website itself but you cannot use "GetAuthorizationHeader()" method to get the token. Instead you can get the token by running the console app once and use a breakpoint to get the string value. Use this value in the code and remove the "GetAuthorizationHeader()" method.
I have used SO to help with several issues in the past. However, I cannot find a solution to something I have been struggling with for 2 days now.
I am a noob, please be kind :)
I have an app that I created using Xamarin Studio, targeted for Android. It is a basic GET request from a Rest Api. It was working perfectly until I realized I was not helping myself when it came time to create the same app in IOS and Windows. Once I changed my project to utilize a PCL I started getting errors, primarily around my RestClient class (originally got from http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp)
From my droid app class:
var apiUser = GetString(Resource.String.apiUser);
var apiPass = GetString(Resource.String.apiPass);
//Get token from API
string token = authenticate(apiUser,apiPass);
public static string authenticate(string apiUser, string apiPass)
{
Authentication Auth = new Authentication ();
try
{
// set json by passing AuthenticationUrl as endpoint, returns json data
var o = JObject.Parse(EntryRepository.getJson(PJTApiUrls.getAuthenticationUrl(apiUser,apiPass)));
Auth.Token = (string)o["Token"];
return Auth.Token;
}
catch (Exception e)
{
// Couldn't do stuff. Log the exception.
// TODO possible timeout, try again, if fails again then return error message
if (e.Message.Contains("400") || e.Message.Contains("401"))
{
string error = string.Format("Invalid credentials, please try again");
return error;
} else {
string error = string.Format ("An error occurred: \r\n{0}", e.Message);
return error;
}
}
}
getAuthenticationUrl gets the api URL.
Here is getJson (in PCL):
public static string getJson(string endpoint)
{
string apiurl = endpoint;
var client = new _RestClient();
client.EndPoint = apiurl;
client.ContentType = "application/json";
client.Method = HttpVerb.GET;
//client.Method = HttpVerb.POST;
client.PostData = "";
//client.PostData = "{postData: value}";
//client.PostData = "{'someValueToPost': 'The Value being Posted'}";
var json = client._MakeRequestAsync();
// to append parameters, pass them into make request:
//var json = client.MakeRequest("?param=0");
return json.ToString();
}
And for the _RestClient class (in PCL):
public async Task<string> _MakeRequestAsync()
{
try {
var request = _MakeRequestAsync ("");
return await request;
}
catch (Exception e){
return e.Message;
}
}
public async Task<string> _MakeRequestAsync(string parameters)
{
var uri = new Uri(EndPoint + parameters);
var request = WebRequest.Create(uri) as HttpWebRequest;
using (var response = await request.GetResponseAsync () as HttpWebResponse) {
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK) {
var message = String.Format ("Request failed. Received HTTP {0}", response.StatusCode);
throw new Exception (message);
}
// grab the response
using (var responseStream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)) {
//using (var responseStream = response.GetResponseStream ()) {
if (responseStream != null)
using (var reader = new StreamReader (responseStream)) {
responseValue = reader.ReadToEnd ();
}
}
return responseValue;
}
}
responseValue is returning null
return await request is saying "Status = Waiting for activation"
I have also had the error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."
But this works if the RestClient class is within Droid (Instead of the shared PCL) and contains the following:
public string MakeRequest ()
{
return MakeRequest ("");
}
public string MakeRequest (string parameters)
{
var request = (HttpWebRequest)WebRequest.Create (EndPoint + parameters);
request.Method = Method.ToString ();
request.ContentLength = 0;
request.ContentType = ContentType;
if (!string.IsNullOrEmpty (PostData) && Method == HttpVerb.POST) {
var bytes = Encoding.GetEncoding ("iso-8859-1").GetBytes (PostData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream ()) {
writeStream.Write (bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse ()) {
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK) {
var message = String.Format ("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException (message);
}
// grab the response
using (var responseStream = response.GetResponseStream ()) {
if (responseStream != null)
using (var reader = new StreamReader (responseStream)) {
responseValue = reader.ReadToEnd ();
}
}
return responseValue;
}
}
I cannot figure this out, any help/guidance is appreciated. Let me know if I can clarify anything.
***** UPDATE ***** Thanks to #milen-pavlov help thus far, here is where I am currently at:
in Android project:
var apiUser = GetString(Resource.String.apiUser);
var apiPass = GetString(Resource.String.apiPass);
//Get token from API
var token = await authenticate(apiUser,apiPass);
lblOutput.Text = token;
calls (also in Android project):
public static async Task<string> authenticate(string apiUser, string apiPass)
{
Authentication Auth = new Authentication ();
try
{
// set json by passing AuthenticationUrl as endpoint, returns json data
var o = JObject.Parse(await EntryRepository.getJson(PJTApiUrls.getAuthenticationUrl(apiUser,apiPass)));
Auth.Token = (string)o["Token"];
return Auth.Token;
}
catch (Exception e)
{
if (e.Message.Contains("400") || e.Message.Contains("401"))
{
string error = string.Format("Invalid credentials, please try again");
return error;
} else {
string error = string.Format ("An error occurred: \r\n{0}", e.Message);
return error;
}
}
}
Calls json class in PCL project:
public static async Task<string> getJson(string endpoint)
{
string apiurl = endpoint;
var client = new _RestClient();
client.EndPoint = apiurl;
client.ContentType = "application/json";
client.Method = HttpVerb.GET;
client.PostData = "";
var json = await client._MakeRequestAsync();
return json;
}
which then calls restclient class in PCL project:
public async Task<string> _MakeRequestAsync()
{
var request = _MakeRequestAsync ("");
return await request;
}
public async Task<string> _MakeRequestAsync(string parameters)
{
var uri = new Uri(EndPoint + parameters);
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
return await response.Content.ReadAsAsync<string>();
};
}
End result/error:
Any guidance is appreciated!
Can you use HttpClient instead?
Sample Get request will look similar to this:
public async Task<string> _MakeRequestAsync(string parameters)
{
var uri = new Uri(EndPoint + parameters);
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
return await result.Content.ReadAsStringAsync();
};
}
I'm trying to POST data in JSON format but the server is rejecting it. It works if I POST in XML and it will reply in either XML or JSON.
The contract is
[ServiceContract]
public interface IService
{
// One string data
[OperationContract]
[WebInvoke(
BodyStyle = WebMessageBodyStyle.Bare,
Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "data")]
string DataPost(Hidden param);
}
// If you get a compilation error, add
// System.Runtime.Serialization to the references
[DataContract(Name = "Hidden", Namespace = "")]
public class Hidden
{
[DataMember]
public string id { get; set; }
}
The implementation is
public class Service : IService
{
public string DataPost(Hidden param)
{
Console.WriteLine("DataPost " + param.id);
return "DataPost said " + param.id;
}
}
On the client side, it is the run of the mill standard stuff.
namespace client
{
enum HttpVerb
{
GET,
POST,
PUT,
DELETE
};
class RestClient
{
// Properties
public string EndPoint { get; set; }
public HttpVerb Method { get; set; }
public string ContentType { get; set; }
public string ParamData { get; set; }
public string PostData { get; set; }
// Methods
public string MakeRequest()
{
var responseValue = string.Empty;
string ep = EndPoint;
if (!string.IsNullOrEmpty(ParamData))
ep += "/" + ParamData;
var request = (HttpWebRequest)WebRequest.Create(ep);
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
// Postdata parameters
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
using (var postStream = request.GetRequestStream())
{
postStream.Write(bytes, 0, bytes.Length);
}
if (PostData.Substring(0, 1) != "<")
request.ContentType = "application/json";
Console.WriteLine("Content type is " + request.ContentType.ToString());
}
// Send request and get response
using (var response = (HttpWebResponse)request.GetResponse())
{
// Did it work?
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// get response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
}
return responseValue;
}
void TalkTo(
HttpVerb in_method,
string in_endPoint,
string in_paramdata,
string in_postdata)
{
Method = in_method;
EndPoint = in_endPoint;
ContentType = "text/xml";
ParamData = in_paramdata;
PostData = in_postdata;
try
{
string response = MakeRequest();
Console.WriteLine("Endpoint: " + EndPoint);
Console.WriteLine("Resp : " + response);
Console.WriteLine();
}
catch (System.Net.WebException e)
{
Console.WriteLine("Endpoint: " + EndPoint);
Console.WriteLine("Failed : " + e.Message);
}
}
static void Main(string[] args)
{
RestClient me = new RestClient();
string endPointPrefix = #"http://localhost:8000/";
me.TalkTo(
HttpVerb.POST,
endPointPrefix + "data",
"",
"<Hidden><id>xml works</id></Hidden>");
string post = "{\"id\":\"json works\"}";
Console.WriteLine("Json string is [" + post + "]");
me.TalkTo(
HttpVerb.POST,
endPointPrefix + "data",
"",
post);
Console.WriteLine("Press <Enter> to terminate");
Console.ReadLine();
}
}
}
On the client side, I'm getting
Content type is text/xml
Endpoint: http://localhost:8000/data
Resp : <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">DataPost said xml works</string>
Json string is [{"id":"json works"}]
Content type is application/json
Endpoint: http://localhost:8000/data
Failed : The remote server returned an error: (400) Bad Request.
Press <Enter> to terminate
When I look at the help, it says that JSON format is allowable but when I try it, it falls over. The trace from the sever debug seems to imply that it is ignoring the application/json and just assuming that everything is xml.
Exception: System.Runtime.Serialization.SerializationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message: There was an error checking start element of object of type System.String. The data at the root level is invalid. Line 1, position 1.
Last few lines of stack trace
System.Runtime.Serialization.XmlObjectSerializer.IsStartObjectHandleExceptions(XmlReaderDelegator reader)
System.Runtime.Serialization.DataContractSerializer.IsStartObject(XmlDictionaryReader reader)
System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.ReadObject(Message message)
All the examples I've looked at on SO and other sites don't add anything special so is it not working because I'm using the VS2013 express?
EDIT It also happens on VS2013 Web Express
EDIT2 Doesn't look like it is isolated to express versions - I've just tried it on VS2010 Professional. It is still using the XMLObjectSerializer to parse JSON and failing miserably.
The fix is to no convert the PostData to bytes
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
{
if (PostData.Substring(0, 1) != "<")
request.ContentType = "application/json";
Console.WriteLine("Content type is " + request.ContentType.ToString());
request.ContentLength = PostData.Length;
using (var postStream = new StreamWriter(request.GetRequestStream()))
{
postStream.Write(PostData);
}
}