ASP.NET Core JSON param always null - c#

I am trying to pass a serialized model from ajax to my controller, but I can't seem to get anything but null to come across. Rather than spend a lot of time talking, I am just going to show code.
The queryDetails is properly formatting the object into { name: val } format, but it is not coming across into the controller.
Summary.cshtml Javascript Code
top of file declaration:
var QueryData = ViewData["QueryData"] as QueryModel;
....
in Js code:
var queryDetails = #Html.Raw(Json.Serialize(#QueryData));
$.ajax({
type: 'POST',
url: '/Home/SummaryRefresh',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { queryDetails },
success: function () {
},
error: function (error) {
alert(error);
}
});
HomeController.cs
[HttpPost]
public IActionResult SummaryRefresh([FromBody] QueryModel queryDetails)
{
// STACKOVERFLOW NOTE: function is hit, but queryDetails is null
if (queryDetails != null)
{
ViewData["QueryData"] = queryDetails;
return View("Summary");
}
else
return BadRequest("Error refreshing view");
}
Startup.cs
...
endpoints.MapControllerRoute(
name: "SummaryRefresh",
pattern: "{controller=Home}/{action=SummaryRefresh}/{queryDetails?}");
...
QueryModel.cs
/// <summary>
/// Holds the query data enetered by user
/// </summary>
public class QueryModel
{
/// <summary>
/// Different ways to view summary mode
/// </summary>
public enum SummaryDisplayMode
{
Full,
Quick
}
/// <summary>
/// Current summary view mode
/// </summary>
private SummaryDisplayMode displayMode = SummaryDisplayMode.Full;
/// <summary>
/// Get/Set display mode
/// </summary>
public SummaryDisplayMode DisplayMode { get => displayMode; set => displayMode = value; }
/// <summary>
/// PO Name filter
/// </summary>
[Display(Name = "Product Owner", Prompt = "Name")]
public string POName { get; set; }
/// <summary>
/// Delivery Order Filter
/// </summary>
[Display(Name = "Delivery Order", Prompt = "Example: [removed]")]
public string DeliveryOrder { get; set; }
/// <summary>
/// Port Number filter
/// </summary>
[RegularExpression(#"^PORT-+([0-9]{3}|[0-9]{4}|[0-9]{5})$", ErrorMessage = "[removed]")]
[Display(Name = "[removed]")]
public string PortNumber { get; set; }
/// <summary>
/// Epic Type filter
/// </summary>
[Display(Name = "Epic Type")]
public string EpicType { get; set; }
/// <summary>
/// Program Increment Filter
/// </summary>
[Display(Name = "Program Increment", Prompt = "Example: 20D")]
public string ProgramIncrement { get; set; }
/// <summary>
/// Whether or not to show resolved capabilities
/// </summary>
[Display(Name = "Show Resolved Ports")]
public bool ShowResolved { get; set; }
/// <summary>
/// Whether or not to show backlogs
/// </summary>
[Display(Name = "Show Backlogs")]
public bool ShowBacklogs { get; set; }
/// <summary>
/// Constructor
/// </summary>
public QueryModel()
{
POName = "";
PortNumber = "";
DeliveryOrder = "";
EpicType = "NA";
ShowResolved = true;
ShowBacklogs = false;
}
}
Debugged paylod:
displayMode=0&poName=jkeller&deliveryOrder=&portNumber=&epicType=NA&programIncrement=&showResolved=true&showBacklogs=false

Solution seems to be to replace
data: { queryDetails },
with
data: JSON.stringify(queryDetails),
Reason is that this line creates an object, not JSON
var queryDetails = #Html.Raw(Json.Serialize(#QueryData));
Hence the object needs to be converted to JSON before performing the POST.

This was tested in Visual Studio, and it is working
[Route("~/Home/SummaryRefresh")]
public IActionResult SummaryRefresh( QueryModel queryDetails)
ajax should be like this
var queryDetails = #Html.Raw(Json.Serialize(#QueryData));
$.ajax({
type: 'POST',
url: '/Home/SummaryRefresh',
data: { queryDetails:queryDetails },
success: function (result) {
},
error: function (error) {
alert(error);
}
});

Related

.NET swagger leave out property from example value

Is there a way to exclude/remove properties from your example value?
I'm using XML comments on my models to provide information on the swagger page with c.IncludeXmlComments
I use the ///<example>Example Value</example> XML tag to set the example values. My request model does not require all the fields to be set by default, but if I don't set an example XML tag the example value is translated to it's type. Looking like this
{
"ID": "string",
"ExampleSetValue": "Example Value"
}
And I want my example value to only contain the ExampleSetValue property so my example value looks like this
{
"ExampleSetValue": "Example Value"
}
This is the swagger setup in my startup
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", openApiInfo);
c.AddSecurityDefinition("Bearer", openApiSecurityScheme);
c.AddSecurityRequirement(openApiSecurityRequirement);
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
My Request Model
public class CreateRequest
{
/// <summary>
/// ID of the user if available
/// </summary>
public string ID { get; set; }
/// <summary>
/// ExampleSetValue
/// </summary>
/// <example>Example Value</example>
public string ExampleSetValue { get; set; }
}
Xml comment seems cannot be used to exclude the property.
If you want to ignore the property, I suggest you use the [System.Text.Json.Serialization.JsonIgnore] attribute. But in this way it will also make your property hidden when you serialize or deserialize the data.
public class CreateRequest
{
/// <summary>
/// ID of the user if available
/// </summary>
[JsonIgnore] //add this..........
public string ID { get; set; }
/// <summary>
/// ExampleSetValue
/// </summary>
/// <example>Example Value</example>
public string ExampleSetValue { get; set; }
}
If you only want to exclude the property from example value, you need custom ISchemaFilter:
Model:
public class CreateRequest
{
/// <summary>
/// ID of the user if available
/// </summary>
[IgnoreDataMember] //add this..........
public string ID { get; set; }
/// <summary>
/// ExampleSetValue
/// </summary>
/// <example>Example Value</example>
public string ExampleSetValue { get; set; }
}
Custom ISchemaFilter:
public class MySwaggerSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema?.Properties == null)
{
return;
}
var ignoreDataMemberProperties = context.Type.GetProperties()
.Where(t => t.GetCustomAttribute<IgnoreDataMemberAttribute>() != null);
foreach (var ignoreDataMemberProperty in ignoreDataMemberProperties)
{
var propertyToHide = schema.Properties.Keys
.SingleOrDefault(x => x.ToLower() == ignoreDataMemberProperty.Name.ToLower());
if (propertyToHide != null)
{
schema.Properties.Remove(propertyToHide);
}
}
}
}
Register the filter:
services.AddSwaggerGen(c =>
{
//......
c.SchemaFilter<MySwaggerSchemaFilter>();
});
I found a different approach which suited my case exactly how I wanted.
You can set an example object on your schema which is of type OpenApiObject.
I Created a Document filter to which loops over the schemas in my swagger.
public class AddExamplesFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var schema in context.SchemaRepository.Schemas)
{
schema.Value.Example = ExampleManager.GetExample(schema.Key);
}
}
}
Created the ExampleManager class which returns the example object I want according to the schema name.
public static OpenApiObject GetExample(string requestModelName)
{
return requestModelName switch
{
"ObjectExample" => ObjectExample.GetExample(),
_ => null
};
}
And as the final step created an example class which corresponds exactly on how I want my example to look like. Where I used the OpenApiObject class
public static class ObjectExample
{
public static OpenApiObject GetExample()
{
return new OpenApiObject
{
["ObjectInsideObject"] = new OpenApiObject
{
["Name"] = new OpenApiString("name"),
},
["ArrayWithObjects"] = new OpenApiArray
{
new OpenApiObject
{
["Object"] = new OpenApiObject
{
["integer"] = new OpenApiInteger(15),
},
["Description"] = new OpenApiString("description")
}
},
["date"] = new OpenApiDate(new DateTime().AddMonths(1)),
["Description"] = new OpenApiString("description"),
};
}
}
Final look on Swagger page

Azure search document results is not binding to model

trying to use azure search documents and bind to a specific model
Model
/// <summary>
/// AzureSearchReturnModel
/// </summary>
public class AzureSearchReturnModel
{
/*// <summary>
/// Gets or sets the module identifier.
/// </summary>
/// <value>
/// The module identifier.
/// </value>
public int ModuleId { get; set; }*/
/// <summary>
/// Gets or sets the end item identifier.
/// </summary>
/// <value>
/// The end item identifier.
/// </value>
[SimpleField(IsFilterable = true)]
public int EndItemId { get; set; }
/*// <summary>
/// Gets or sets the end item type identifier.
/// </summary>
/// <value>
/// The end item type identifier.
/// </value>
public int EndItemTypeId { get; set; }
/// <summary>
/// Gets or sets the name of the file.
/// </summary>
/// <value>
/// The name of the file.
/// </value>
public string FileName { get; set; }
/// <summary>
/// Gets or sets the file extension.
/// </summary>
/// <value>
/// The file extension.
/// </value>
public string FileExtension { get; set; }
/// <summary>
/// Gets or sets the name of the module type.
/// </summary>
/// <value>
/// The name of the module type.
/// </value>
public string ModuleTypeName { get; set; }
/// <summary>
/// Gets or sets the size of the file.
/// </summary>
/// <value>
/// The size of the file.
/// </value>
public long FileSize { get; set; }*/
}
Here is a picture of my azure search settings on portal.azure for my index:
Here is the code I'm calling to obtain the results:
/// <summary>
/// Gets the files azure BLOB results from azure search.
/// </summary>
/// <param name="moduleId">The module identifier.</param>
/// <param name="endItemId">The end item identifier.</param>
/// <param name="endItemTypeId">The end item type identifier.</param>
/// <returns></returns>
public IEnumerable<FileManagerFileSystemItem> GetFilesAzureBlobResultsFromAzureSearch(int moduleId, int endItemId, int endItemTypeId)
{
SearchOptions options = new SearchOptions()
{
Filter = string.Format("endItemId eq '82'", endItemId),
/*Filter = string.Format("moduleId eq {0} and endItemId eq {1} and endItemTypeId eq {2}", moduleId.ToString(), endItemId.ToString(), endItemTypeId.ToString()),*/
};
SearchResults<AzureSearchReturnModel> results;
SearchClient searchClient = AzureKeyVaultUtilities.CreateSearchClientForQueries();
options.Select.Add("endItemId");
/*options.Select.Add("moduleId");
options.Select.Add("endItemId");
options.Select.Add("endItemTypeId");
options.Select.Add("moduleType");
options.Select.Add("fileName");
options.Select.Add("fileExtension");
options.Select.Add("metadata_storage_size");*/
results = searchClient.Search<AzureSearchReturnModel>("*", options);
return Enumerable.Empty<FileManagerFileSystemItem>();
}
The code runs without any issues, but my data is not binding to my model.
What am I doing wrong?
It appears the count is right? When I run the query via portal.azure.us it shows me 4 results:
Based on the info you provided, I created an index and write a demo for you.This is my index:
And my code below:
First I upload some docs and then query them with binding to a specific model as you want :
using System;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
namespace AzureSearchTest
{
class Program
{
static void Main(string[] args)
{
var searchServiceName = "";
var cred = "";
var indexName = "";
SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(cred));
ISearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);
//UploadDocuments(indexClient);
var results = indexClient.Documents.Search<AzureSearchReturnModel>("*");
Console.WriteLine(results.Results.Count);
}
private static void UploadDocuments(ISearchIndexClient indexClient) {
var AzureSearchReturnModels = new AzureSearchReturnModel[] {
new AzureSearchReturnModel(){
ModuleId = "1" ,
EndItemId = "100",
EndItemTypeId = "200",
FileName= "test file 1",
FileExtension ="txt",
ModuleTypeName = "demo",
FileSize = 20000
},
new AzureSearchReturnModel(){
ModuleId = "2" ,
EndItemId = "100",
EndItemTypeId = "200",
FileName= "test file 2",
FileExtension ="aaa",
ModuleTypeName = "demo",
FileSize = 50000
},
new AzureSearchReturnModel(){
ModuleId = "3" ,
EndItemId = "100",
EndItemTypeId = "200",
FileName= "test file 3",
FileExtension ="bbb",
ModuleTypeName = "demo",
FileSize = 60000
}
};
var batch = IndexBatch.Upload(AzureSearchReturnModels);
indexClient.Documents.Index(batch);
}
}
public class AzureSearchReturnModel
{
[Newtonsoft.Json.JsonProperty(PropertyName = "moduleId")]
public String ModuleId { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "endItemId")]
public String EndItemId { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "endItemTypeId")]
public String EndItemTypeId { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "fileName")]
public string FileName { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "fileExtension")]
public string FileExtension { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "moduleType")]
public string ModuleTypeName { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "metadata_storage_size")]
public long FileSize { get; set; }
}
}
Result:

Array types with <example> tag not working with Swagger (swashbuckle.aspnetcore)

I am using the summary and example tags for the swagger documentation.
I have a problem with the tag, it's not recognized by swagger when I use array :
I use swashbuckle.aspnetcore package Nuget.
Example :
[DataContract]
public class HeaderResponse
{
/// <summary>
/// Statut code
/// </summary>
///<example>400</example>
[DataMember]
public int StatusCode { get; set; }
/// <summary>
/// Title
/// </summary>
/// <example>Erreur sur methode1</example>
[DataMember]
public string Title { get; set; }
/// <summary>
/// List of errors
/// </summary>
///<example>["entry1", "entry2", "entry3"]</example>
[DataMember]
public List<string> ErrorList { get; } = new List<string>();
}
On swagger documentation, array is not interpreted :
I found others solutions by using ISchemaFilter like this :
public class SwaggerExcludeFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
switch (context.Type.Name)
{
case "HeaderResponse":
foreach (var property in schema.Properties)
{
if (property.Value.Type == "array")
{
var array = new OpenApiArray();
array.Add(new OpenApiString("item1"));
array.Add(new OpenApiString("item2"));
array.Add(new OpenApiString("item3"));
property.Value.Example = array;
}
}
break;
}
}
}
Is there no other way than to use ISchemaFilter to handle tags of type array?
You can try to do like this:
public List<string> ErrorList { get; } = new List<string>{"entry1", "entry2", "entry3"};
or:
[DataContract]
public class HeaderResponse
{
public HeaderResponse()
{
ErrorList = new List<string> {"entry1", "entry2", "entry3" };
}
/// <summary>
/// Statut code
/// </summary>
///<example>400</example>
[DataMember]
public int StatusCode { get; set; }
/// <summary>
/// Title
/// </summary>
/// <example>Erreur sur methode1</example>
[DataMember]
public string Title { get; set; }
/// <summary>
/// List of errors
/// </summary>
[DataMember]
public List<string> ErrorList { get; set; }
}
Here is a demo:
[HttpPost("TestPar")]
public IActionResult TestPar(HeaderResponse h)
{
return Json(h);
}
result:
The quotes must be escaped using "
/// <summary>
/// List of errors
/// </summary>
///<example>["entry1","entry2","entry3"]</example>
[DataMember]
public List<string> ErrorList { get; } = new List<string>();
I have the same problem and I try this. you can add a condition on the name of the property and add the null return in order not to lose the example on the other properties. But the best solution would be to be able to find a generic solution. How is it possible to get the example tag and the property name with ISchemaFilter ? This is my solution :
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
schema.Example = GetExampleOrNullFor(schema, context);
}
private IOpenApiAny GetExampleOrNullFor(OpenApiSchema schema, SchemaFilterContext context)
{
switch (context.Type.Name)
{
case "MyClass":
foreach (var property in schema.Properties)
{
//Array property, which wraps its elements
if (property.Value.Type == "array")
{
if (property.Key == "MyProperty1")
{
var array = new OpenApiArray();
array.Add(new OpenApiString("item1"));
array.Add(new OpenApiString("item2"));
property.Value.Example = array;
}
else if (property.Key == "MyProperty2")
{
var array = new OpenApiArray();
array.Add(new OpenApiString("item1"));
property.Value.Example = array;
}
}
}
return null;
default:
return null;
}
}
Support for examples using XML comments on arrays was added in Swashbuckle.AspNetCore version 6.0.0.
It's mentioned in this GitHub issue and their documentation shows the following example:
/// <summary>
/// The sizes the product is available in
/// </summary>
/// <example>["Small", "Medium", "Large"]</example>
public List<string> Sizes { get; set; }

How to read Xml to Linq from service

I have a string data get from service Location Xml
I want to read response text and return ObservableCollection
public void SearchLocation(string address)
{
var webclient = new WebClient();
if (address != "")
{
string url =
string.Format(
#"http://dev.virtualearth.net/REST/v1/Locations?countryRegion=Vietnam&adminDistrict=Ha Noi&locality={0}&o=xml&key={1}",
address, BingMapKey);
webclient.DownloadStringAsync(new Uri(url));
webclient.DownloadStringCompleted += WebclientOnDownloadStringCompleted;
}
}
private void WebclientOnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string data = e.Result;
ReadXml(data);
}
private void ReadXml(string data)
{
_locations.Clear();
XDocument document = XDocument.Parse(data);
var locations = from loca in document.Descendants("Location")
select
new Location(loca.Element("Name").Value,
loca.Element("Point").Element("Latitude").Value,"1",
"1", "1", "1", "1");
_locations = (ObservableCollection<Location>) locations;
}
}
Class Location:
public class Location
{
/// <summary>
/// Tên địa điểm
/// </summary>
public string Name { get; set; }
/// <summary>
/// Vĩ độ
/// </summary>
public double Latitude { get; set; }
/// <summary>
/// Kinh độ
/// </summary>
public double Longitute { get; set; }
/// <summary>
/// Vĩ độ Nam
/// </summary>
public double SouthLatitude { get; set; }
/// <summary>
/// Kinh độ Tây
/// </summary>
public double WestLongtitue { get; set; }
/// <summary>
/// Vĩ độ Bắc
/// </summary>
public double NorthLatitude { get; set; }
/// <summary>
/// Kinh độ Tây
/// </summary>
public double EastLongitude { get; set; }
/// <summary>
/// Khởi tạo Location
/// </summary>
/// <param name="name">tên địa điểm</param>
/// <param name="latitue">vĩ độ</param>
/// <param name="longitude">kinh độ</param>
/// <param name="southLatitude">vĩ độ nam</param>
/// <param name="westLongitude">kinh độ tây</param>
/// <param name="northLatitude">vĩ độ bắc</param>
/// <param name="eastLongitude">kinh độ đông</param>
public Location(string name, string latitue, string longitude, string southLatitude, string westLongitude,
string northLatitude, string eastLongitude)
{
Name = name;
Latitude = Convert.ToDouble(latitue);
Longitute = Convert.ToDouble(longitude);
SouthLatitude = Convert.ToDouble(southLatitude);
NorthLatitude = Convert.ToDouble(northLatitude);
WestLongtitue = Convert.ToDouble(westLongitude);
EastLongitude = Convert.ToDouble(eastLongitude);
}
}
I read and _location return null, where are errors?
You can cast IEnumerable<Location> which is a result of LINQ to XML query to ObservableCollection<Location> directly.
_locations = (ObservableCollection<Location>) locations;
Just add all elements from query result collection into existing ObservableCollection:
foreach(var location in locations)
_locations.Add(location);
Update
There is also namespace problem in your code. Try that one:
XDocument document = XDocument.Parse(data);
var ns = XNamespace.Get("http://schemas.microsoft.com/search/local/ws/rest/v1");
var locations = from loca in document.Descendants(ns + "Location")
select
new Location(loca.Element(ns + "Name").Value,
loca.Element(ns + "Point").Element(ns + "Latitude").Value, "1",
"1", "1", "1", "1");

Upload JSON via WebClient

I have a web app with that is using JQuery to interact with my backend. The backend successfully accepts JSON data. For instance, I can successfully send the following JSON:
{ "id":1, "firstName":"John", "lastName":"Smith" }
I now have a Windows Phone app that must hit this backend. I need to pass this same JSON via a WebClient. Currently I have the following, but i'm not sure how to actually pass the JSON.
string address = "http://www.mydomain.com/myEndpoint;
WebClient myService = new WebClient();
utilityService.UploadStringCompleted += new UploadStringCompletedEventHandler(utilityService_UploadStringCompleted);
utilityService.UploadStringAsync(address, string.Empty);
Can someone tell me what I need to do?
Although the question is already answered, I thought it would be nice to share my simple JsonService, based on the WebClient:
Base class
/// <summary>
/// Class BaseJsonService.
/// </summary>
public abstract class BaseJsonService
{
/// <summary>
/// The client
/// </summary>
protected WebClient client;
/// <summary>
/// Gets the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public abstract void Get<TResponse>(string url, Action<TResponse> onComplete, Action<Exception> onError);
/// <summary>
/// Sends the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="jsonData">The json data.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public abstract void Post<TResponse>(string url, string jsonData, Action<TResponse> onComplete, Action<Exception> onError);
}
Service implementation
/// <summary>
/// Class JsonService.
/// </summary>
public class JsonService : BaseJsonService
{
/// <summary>
/// Gets the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public override void Get<TResponse>(string url, Action<TResponse> onComplete, Action<Exception> onError)
{
if (client == null)
client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
TResponse returnValue = default(TResponse);
try
{
returnValue = JsonConvert.DeserializeObject<TResponse>(e.Result);
onComplete(returnValue);
}
catch (Exception ex)
{
onError(new JsonParseException(ex));
}
};
client.Headers.Add(HttpRequestHeader.Accept, "application/json");
client.Encoding = System.Text.Encoding.UTF8;
client.DownloadStringAsync(new Uri(url));
}
/// <summary>
/// Posts the specified URL.
/// </summary>
/// <typeparam name="TResponse">The type of the attribute response.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="jsonData">The json data.</param>
/// <param name="onComplete">The configuration complete.</param>
/// <param name="onError">The configuration error.</param>
public override void Post<TResponse>(string url, string jsonData, Action<TResponse> onComplete, Action<Exception> onError)
{
if (client == null)
client = new WebClient();
client.UploadDataCompleted += (s, e) =>
{
if (e.Error == null && e.Result != null)
{
TResponse returnValue = default(TResponse);
try
{
string response = Encoding.UTF8.GetString(e.Result);
returnValue = JsonConvert.DeserializeObject<TResponse>(response);
}
catch (Exception ex)
{
onError(new JsonParseException(ex));
}
onComplete(returnValue);
}
else
onError(e.Error);
};
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Encoding = System.Text.Encoding.UTF8;
byte[] data = Encoding.UTF8.GetBytes(jsonData);
client.UploadDataAsync(new Uri(url), "POST", data);
}
}
Example usage
/// <summary>
/// Determines whether this instance [can get result from service].
/// </summary>
[Test]
public void CanGetResultFromService()
{
string url = "http://httpbin.org/ip";
Ip result;
service.Get<Ip>(url,
success =>
{
result = success;
},
error =>
{
Debug.WriteLine(error.Message);
});
Thread.Sleep(5000);
}
/// <summary>
/// Determines whether this instance [can post result automatic service].
/// </summary>
[Test]
public void CanPostResultToService()
{
string url = "http://httpbin.org/post";
string data = "{\"test\":\"hoi\"}";
HttpBinResponse result = null;
service.Post<HttpBinResponse>(url, data,
response =>
{
result = response;
},
error =>
{
Debug.WriteLine(error.Message);
});
Thread.Sleep(5000);
}
}
public class Ip
{
public string Origin { get; set; }
}
public class HttpBinResponse
{
public string Url { get; set; }
public string Origin { get; set; }
public Headers Headers { get; set; }
public object Json { get; set; }
public string Data { get; set; }
}
public class Headers
{
public string Connection { get; set; }
[JsonProperty("Content-Type")]
public string ContentType { get; set; }
public string Host { get; set; }
[JsonProperty("Content-Length")]
public string ContentLength { get; set; }
}
Just to share some knowledge!
Good luck!
Figured it out. I was forgetting the following:
myService.Headers.Add("Content-Type", "application/json");

Categories

Resources