Expected Json Format from REST WCF - asp.net

I have developed one REST WCF and to test post method I had made simple call and would like to return output in json format. Following is my SVC and code behind
Iservice:
[OperationContract ]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "heroku/resources")]
User PostData(User objUser);
Service.cs:
public User PostData(User objUser)
{
User usr = new User();
usr.id = 100;
List<string> lst = new List<string>();
lst.Add("MY_URL");
lst.Add("MY");
usr.config = lst;
usr.message = "msg";
return usr;
}
User class :
[DataContract(Namespace = "http://localhost/RestWCFDemo/UserData")]
public class User
{
[DataMember]
[JsonProperty]
public int id
{
get;
set;
}
[DataMember]
[JsonProperty]
public List<string> config
{
get;
set;
}
[DataMember]
[JsonProperty]
public string message
{
get;
set;
}
}
Now from aspx code behind file I have called this service and assign response of that service to textbox and result I am getting is: {"config":["MY_URL","MY"],"id":100,"message":"msg"} however I expected output in this format {"config":{...},"id":100,"message":"msg"} , main problem is [ ] instead of { }.

Hey Arun change from list to class object then you can get {} instead of []..

Related

Integration Testing Forms with Nested Objects

I am using .NET Core with Boilerplate. I'm trying to unit test some new forms that require that I have nested objects with properties. The Integration Tests use AbpAspNetCoreIntegratedTestBase<Startup> which uses an instance of both HttpClient and TestServer. The client has various types of methods at its disposal. There are GetAsync, PostAsync, SendSync and PutAsync methods just to name a few.
I thought I had gotten comfortable with some of the methods and helper methods in this frame work and have been successful thus far. However, I have a form with an Model called Vendor, the Vendor has an Address Model as part of the view model. This is so I can reuse the Address View Model with other items in the application that also require Address(es).
One of the helpers that is used with BoilerPlate is GetUrl<TController>(string actionName, object queryStringParamsAsAnonymousObject) Since this is a Post from a form I'm attempting to use public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content) No matter what I'm attempting to do, I'm getting a 400 Bad Request response and my test fails before it even gets inside the controller method. I'm at a loss of how to handle this.
Here are my Models:
VendorViewModel:
[AutoMap(typeof(Domains.Vendor))]
public class VendorViewModel : BaseViewModelEntity
{
[Required]
public string Name { get; set; }
[Required]
public string PointOfContact { get; set; }
[Required]
public string Email { get; set; }
[Required]
public int AddressId { get; set; }
//[Required]
//public string Address1 { get; set; }
//public string Address2 { get; set; }
//public string Address3 { get; set; }
//[Required]
//public string City { get; set; }
//[Required]
//public int State { get; set; }
//[Required]
//public string Zip { get; set; }
//[Required]
//public string Phone { get; set; }
//public string Fax { get; set; }
public AddressViewModel VendorAddress { get; set; }
public VendorViewModel()
{
VendorAddress = new AddressViewModel();
}
public VendorViewModel(VendorDto vendor)
{
Id = vendor.Id;
Name = vendor.Name;
IsActive = vendor.IsActive;
PointOfContact = vendor.PointOfContact;
Email = vendor.Email;
AddressId = vendor.AddressId;
CreatorUserId = vendor.CreatorUserId;
CreationTime = vendor.CreationTime;
DeleterUserId = vendor.DeleterUserId;
DeletionTime = vendor.DeletionTime;
LastModificationTime = vendor.LastModificationTime;
LastModifierUserId = vendor.LastModifierUserId;
//Address1 = vendor.Address.Address1;
//Address2 = vendor.Address.Address2;
//Address3 = vendor.Address.Address3;
//City = vendor.Address.City;
//State = vendor.Address.State;
//Zip = vendor.Address.Zip;
//Phone = vendor.Address.Phone;
//Fax = municipalities.Address.Fax;
VendorAddress = new AddressViewModel()
{
Id = vendor.Address.Id,
Address1 = vendor.Address.Address1,
Address2 = vendor.Address.Address2,
Address3 = vendor.Address.Address3,
City = vendor.Address.City,
State = vendor.Address.State,
Zip = vendor.Address.Zip,
Phone = vendor.Address.Phone,
Fax = vendor.Address.Fax,
CreationTime = vendor.Address.CreationTime,
};
}
}
Address View Model:
public class AddressViewModel : BaseViewModelEntity
{
[Required]
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
[Required]
public string City { get; set; }
[Required]
public int State { get; set; }
[Required]
public string Zip { get; set; }
[Required]
public string Phone { get; set; }
public string Fax { get; set; }
public AddressViewModel()
{
}
public AddressViewModel(AddressDto address)
{
Id = address.Id;
Address1 = address.Address1;
Address2 = address.Address2;
Address3 = address.Address3;
City = address.City;
State = address.State;
Zip = address.Zip;
Phone = address.Phone;
Fax = address.Phone;
CreatorUserId = address.CreatorUserId;
CreationTime = address.CreationTime;
DeleterUserId = address.DeleterUserId;
DeletionTime = address.DeletionTime;
LastModificationTime = address.LastModificationTime;
LastModifierUserId = address.LastModifierUserId;
}
}
I have my Test set up with xUnit
//Arrange
//Add Client Headers so User Auth and Permission Checkers work correctly
Client.DefaultRequestHeaders.Add("my-name", "admin");
Client.DefaultRequestHeaders.Add("my-id", "2");
//set up test data
var addressViewModel = new AddressViewModel()
{
Address1 = "123 This Way", City = "Arlington", State = 44, Zip = "76001", Phone = "8175555555",
CreationTime = DateTime.Now
};
var viewModelSave = new VenderViewModel()
{
Name = "Controller Test Name",
PointOfContact = "Tom Jerry",
Email = "Tom.Jerry#yolo.com",
CreationTime = DateTime.Now,
LastModificationTime = null,
IsActive = true,
AddressId = 0,
VendorAddress = addressViewModel
//Address1 = "123 This Way",
//City = "Arlington",
//State = 44,
//Zip = "76001",
//Phone = "8175555555"
};
/* This is an attempt to use string interpolation to create querystring parameters */
//var rawData =
// $"?Name={viewModelSave.Name}&Id={viewModelSave.Id}&PointOfContat=${viewModelSave.PointOfContact}&Email={viewModelSave.Email}&CreationTime={DateTime.Now}" +
// $"&LastModificationTime=&IsActive={viewModelSave.IsActive}&AddressId={viewModelSave.AddressId}&VendorAddress.Id={viewModelSave.VendorAddress.Id}&VendorAddress.Address1={viewModelSave.VendorAddress.Address1}" +
// $"&VendorAddress.City={viewModelSave.VendorAddress.City}&VendorAddress.State={viewModelSave.VendorAddress.State}&VendorAddress.Zip={viewModelSave.VendorAddress.Zip}&VendorAddress.Phone={viewModelSave.VendorAddress.Phone}" +
// $"&VendorAddress.CreationTime={DateTime.Now}&VendorAddress.IsActive={viewModelSave.VendorAddress.IsActive}";
/*This is an attempt to create a json object that could be serialize into an object as the "queryStringParamsAsAnonymousObject" that can be used in the GetUrl Helper method below */
var rawData = $"{{'Name':'Controller Test Name','PointOfContact':'Tom Jerry', 'Email': 'Tom.Jerry#yolo.com',"
+ "'CreationTime':'" + DateTime.Now + "','LastModificationTime':'','IsActive' : 'true','AddressId':'0','Address.Address1':'123 This Way',"
+ "'Address.City':'Arlington','Address.State':'44','Address.Zip':'76001','Address.Phone':'8175555556','Address.IsActive':'true'}";
var jsonData = JsonConvert.DeserializeObject(rawData);
//Serialize ViewModel to send with Post as part of the HttpContent object
var data = JsonConvert.SerializeObject(viewModelSave);
var vendorAddress = new
{
viewModelSave.vendorAddress.Id,
viewModelSave.vendorAddress.Address1,
viewModelSave.vendorAddress.City,
viewModelSave.vendorAddress.State,
viewModelSave.vendorAddress.Zip,
viewModelSave.vendorAddress.Phone,
viewModelSave.vendorAddress.IsActive,
viewModelSave.vendorAddress.CreationTime
};
//actually get the url from helper method (with various attempts at creating an anonymousObject directly
var url = GetUrl<VendorController>(nameof(VendorController.SaveVendor),
new
{
viewModelSave.Id,
viewModelSave.Name,
viewModelSave.PointOfContact,
viewModelSave.Email,
viewModelSave.CreationTime,
viewModelSave.LastModificationTime,
viewModelSave.IsActive,
viewModelSave.AddressId,
vendorAddress
//VendorAddress_Address1 = vendorAddress.Address1,
//VendorAddress_Id = vendorAddress.Id,
//VendorAddress_City = vendorAddress.City,
//VendorAddress_State = vendorAddress.State,
//VendorAddress_Zip = vendorAddress.Zip,
//VendorAddress_Phone = vendorAddress.Phone,
//VendorAddress_IsActive = vendorAddress.IsActive,
//VendorAddress = new
//{
// viewModelSave.VendorAddress.Id,
// viewModelSave.VendorAddress.Address1,
// viewModelSave.VendorAddress.City,
// viewModelSave.VendorAddress.State,
// viewModelSave.VendorAddress.Zip,
// viewModelSave.VendorAddress.Phone,
// viewModelSave.VendorAddress.IsActive,
// viewModelSave.VendorAddress.CreationTime
//},
//viewModelSave.Address1,
//viewModelSave.City,
//viewModelSave.State,
//viewModelSave.Zip,
//viewModelSave.Phone
}
);
var content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
var message = new HttpRequestMessage {
Content = content,
Method = HttpMethod.Post,
RequestUri = new Uri("http://localHost" + url)
};
//Act
var response = await PostResponseAsObjectAsync<AjaxResponse>(url, content);
//Assert
var count = UsingDbContext(context => { return context.Municipalities.Count(x => x.IsActive); });
response.ShouldBeOfType<AjaxResponse>();
response.Result.ShouldNotBeNull();
count.ShouldBe(3);
}
As I attempt to debug what is happening. I've noticed that the VendorAddress properties that are sent via the test request do not match what the actual form post looks like when parsed in Chrome developer tools. In Chrome I see (example:
PointOfContact:"Tom Jerry"
IsActive:True
VendorAddress.Address1:"123 This Way"
VendorAddress.City: "Arlington")
I cannot get my test data into that same format, therefore its not binding correctly to my view models on post, and thus returns a 400 response and fails the test.
I have gotten it to work if I remove the Address View Model all together and put those properties as properties of the VendorViewModel. However, I would run into the same if not similar issue if I'm attempting to save a collection of objects along with the main view model.
I feel like there has to be a way to submit test form data via integration tests with boilerplate. I just need some missing piece to this puzzle.
The Solution that is working for both Post and Send Requests:
.NET Core has a QueryHelper class that will take a dictionary and a uri string and convert it into a url with querystring parameters. QueryHelpers.AddQueryString(string uri, IDictionary queryString) This is part of Microsoft.AspNetCore.WebUtilities.
Using this method I was able to properly prepare my formData. For a Post Request the Test would look like this
//Arrange
//Add Client Headers so User Auth and Permission Checkers work correctly
Client.DefaultRequestHeaders.Add("my-name", "admin");
Client.DefaultRequestHeaders.Add("my-id", "2");
//set up test data
var rawData = new Dictionary<string, string>(){{ "Id", "0"}, {"Name", "Controller Test Name"}, {"PointOfContact", "Tom Jerry"}
, {"Email", "Tom.Jerry#yolo.comy"}, {"CreationTime", $"{DateTime.Now}"}, {"LastModificationTime", ""}, {"IsActive", "true"}, {"AddressId", "0"}
, {"VendorAddress.Id", "0"}, {"VendorAddress.Address1", "123 This Way"}, {"VendorAddress.City", "Arlington"}, {"VendorAddress.State", "44"}, {"VendorAddress.Zip", "76001"}
, {"VendorAddress.Phone", "8175555555"}, {"VendorAddress.Fax", ""}, {"VendorAddress.IsActive", "true"}, {"VendorAddress.CreationTime", $"{DateTime.Now}"}, {"VendorAddress.LastModificationTime", ""}
};
var jsonData = JsonConvert.DeserializeObject(rawData);
//Serialize ViewModel to send with Post as part of the HttpContent object
var data = JsonConvert.SerializeObject(viewModelSave);
//actually get the url from helper method
var url = GetUrl<VendorController>(nameof(VendorController.SaveVendor));
var content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
//Act
var response = await PostResponseAsObjectAsync<AjaxResponse>(url, content);
//Assert
var count = UsingDbContext(context => { return context.Municipalities.Count(x => x.IsActive); });
response.ShouldBeOfType<AjaxResponse>();
response.Result.ShouldNotBeNull();
count.ShouldBe(3);
Send Request Test would look like this
//Arrange
//Add Client Headers so User Auth and Permission Checkers work correctly
Client.DefaultRequestHeaders.Add("my-name", "admin");
Client.DefaultRequestHeaders.Add("my-id", "2");
//set up test data
var rawData = new Dictionary<string, string>(){{ "Id", "0"}, {"Name", "Controller Test Name"}, {"PointOfContact", "Tom Jerry"}
, {"Email", "Tom.Jerry#yolo.comy"}, {"CreationTime", $"{DateTime.Now}"}, {"LastModificationTime", ""}, {"IsActive", "true"}, {"AddressId", "0"}
, {"VendorAddress.Id", "0"}, {"VendorAddress.Address1", "123 This Way"}, {"VendorAddress.City", "Arlington"}, {"VendorAddress.State", "44"}, {"VendorAddress.Zip", "76001"}
, {"VendorAddress.Phone", "8175555555"}, {"VendorAddress.Fax", ""}, {"VendorAddress.IsActive", "true"}, {"VendorAddress.CreationTime", $"{DateTime.Now}"}, {"VendorAddress.LastModificationTime", ""}
};
var jsonData = JsonConvert.DeserializeObject(rawData);
//Serialize ViewModel to send with Post as part of the HttpContent object
var data = JsonConvert.SerializeObject(viewModelSave);
//actually get the url from helper method
var url = GetUrl<VendorController>(nameof(VendorController.SaveVendor));
var content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
var message = new HttpRequestMessage {
Content = content,
Method = HttpMethod.Post,
RequestUri = new Uri("http://localHost" + url)
};
//Act
var response = await SendResponseAsObjectAsync<AjaxResponse>(message);
//Assert
var count = UsingDbContext(context => { return context.Municipalities.Count(x => x.IsActive); });
response.ShouldBeOfType<AjaxResponse>();
response.Result.ShouldNotBeNull();
count.ShouldBe(3);

Data Annotations to sanitize request and response before logging

I'm looking for a reliable solution to log details of requests and responses made to and from our controllers. However, some of the data passing through contains sensitive information that should not be written to a log.
In the controller, the inbound request is bound to a single model from the request body, and as the request is answered, a single model is passed to the Ok() result like this (very simplified):
[HttpGet]
[Route("Some/Route")]
public IHttpActionResult SomeController([FromBody] RequestType requestObj)
{
ResponseType responseObj = GetResponse(requestObj)
return this.Ok(responseObj);
}
Now my goal is to somehow log the contents of the request and response object at the beginning and end of the controller, respectively. What I would like to do is bind the models first, then log out their attributes. An example of the RequestType is something like:
public class RequestType
{
public string SomeAttribute { get; set; }
public string AnotherAttribute { get; set; }
public string Password{ get; set; }
}
And the log would look something like:
[date-time] Request to SomeController:
SomeAttribute: "value_from_request"
AnotherAttribute: "another_value"
Password: "supersecret123"
Now clearly we don't want the password to be logged. So I would like to create a custom data annotation that would not log certain fields. Its use would look like this (updated RequestType):
public class RequestType
{
public string SomeAttribute { get; set; }
public string AnotherAttribute { get; set; }
[SensitiveData]
public string Password{ get; set; }
}
Where would I start with this? I'm not incredibly familliar with .NET, but know that there are many sort of magic classes that can be subclassed to override some of their functionality. Is there any such class that can help here? Even better, is there any way to do this during the model binding? So we could catch errors that occur during model binding as well?
We should be able to achieve what you're looking for with an ActionFilterAttribute.
Capture Requests Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class CaptureRequestsAttribute : ActionFilterAttribute // *IMPORTANT* This is in the System.Web.Http.Filters namespace, not System.Web.Mvc
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var messages = actionContext.ActionArguments.Select(arg => GetLogMessage(arg.Value));
var logMessage = $"[{DateTime.Now}] Request to " +
$"{actionContext.ControllerContext.Controller}]:\n{string.Join("\n", messages)}";
WriteToLog(logMessage);
base.OnActionExecuting(actionContext);
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var result = actionExecutedContext.Response.Content as ObjectContent;
var message = GetLogMessage(result?.Value);
var logMessage = $"[{DateTime.Now}] Response from " +
$"{actionExecutedContext.ActionContext.ControllerContext.Controller}:\n{message}";
WriteToLog(logMessage);
base.OnActionExecuted(actionExecutedContext);
}
private static void WriteToLog(string message)
{
// todo: write you logging stuff here
}
private static string GetLogMessage(object objectToLog)
{
if (objectToLog == null)
{
return string.Empty;
}
var type = objectToLog.GetType();
var properties = type.GetProperties();
if (properties.Length == 0)
{
return $"{type}: {objectToLog}";
}
else
{
var nonSensitiveProperties = type
.GetProperties()
.Where(IsNotSensitiveData)
.Select(property => $"{property.Name}: {property.GetValue(objectToLog)}");
return string.Join("\n", nonSensitiveProperties);
}
}
private static bool IsNotSensitiveData(PropertyInfo property) =>
property.GetCustomAttributes<SensitiveDataAttribute>().Count() == 0;
}
Sensitive Data Attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class SensitiveDataAttribute : Attribute
{
}
Then, you can just add it to your WebApi controller (or a specific method in it):
[CaptureRequests]
public class ValuesController : ApiController
{
// .. methods
}
And finally your models can just add the SensitiveDataAttribute:
public class TestModel
{
public string Username { get; set; }
[SensitiveData]
public string Password { get; set; }
}
This does not make use of DataAnnotations,however, One way that comes to mind would be to use the serialization. If your payload is within a reasonable size you could serialize and deserialize your RequestType class when reading and writing to/from a log. This would require a custom serialization format or making use of the default, xml.
[Seriliazeble()]
public class RequestType
{
public string SomeAttribute { get; set; }
public string AnotherAttribute { get; set; }
[NonSerialized()]
public string Password{ get; set; }
}
Using the above attribute will omit Password from serialization. Then you copuld proceed to Logger.Log(MySerializer.Serialize(MyRequest)); and your sensitive data will be omitted.
This link describes the approach in detail.
For xml serialization, simply use the XmlSerializer class.
public class MySerializationService
{
public string SerializeObject(object item)
{
XmlSerializer serializer = new XmlSerializer(item.GetType());
System.IO.MemoryStream aMemStr = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(aMemStr, null);
serializer.Serialize(writer, item);
string strXml = System.Text.Encoding.UTF8.GetString(aMemStr.ToArray());
return strXml;
}
public object DeSerializeObject(Type objectType, string objectString)
{
object obj = null;
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(objectString));
return obj;
}
}
Then using the above or similar methods you can read and write in a custom format.
Write :
string logData=new MySerializationService().SerializeObject(myRequest);
Read :
RequestType loggedRequest= (RequestType)new MySerializationService().DeSerializeObject(new RequestType().GetType(), logData);

SignalR - how to invoke client method from a class in a different assembly?

Can anyone out there help me to understand
how to invoke the client method from server method using SignalR The server class resides in an CustomEvent handler in a different assembly.
I tried 3 different methods to invoke the method:
I named my hub as [HubName("notificationhub")]
Method1
Clients.addMessage(message);
This gives "Cannot perform runtime binding on a null reference"
Method 2
IHubContext context1 = GlobalHost.ConnectionManager.GetHubContext("notificationhub");
context1.Clients.addMessage('hello');
The client remained silent.
Method3
var hubConnection = new HubConnection("http://localhost:21120/");
var notification= hubConnection.CreateProxy("notificationhub");
hubConnection.Start().Wait();
notification.Invoke("Send", "Hello").Wait();
This method gives error : {"The remote server returned an error: (500) Internal Server Error."} To my surprise, i am able to invoke this method from a console application using the 3rd method.
what is the best solution for implementing this and what is the reason why i am not able to invoke the client method? Can anyone help me with this?
Regards
Vince
Here is how Im doing it, a bit a hack, but it works. It only works when calling hub from a controller, otherwise it wont work. Use UpdateHubFromController method.
public class UpdateFeedActivity : Hub
{
readonly IHubContext _hubContext ;
public UpdateFeedActivity()
{
_hubContext = _hubContext ?? GlobalHost.ConnectionManager.GetHubContext<UpdateFeedActivity>();
}
public void UpdateFeed(string groupname, string itemId, Enums.FeedActivityTypes activityType,
string userId="",
string actionResult1="",
string actionResult2="",
string actionResult3="")
{
Clients.Group(groupname).updateMessages(new FeedHubResponse
{
ItemId = itemId,
ActivityType = activityType.ToString(),
UserId = userId,
ActionResult1 = actionResult1,
ActionResult2 = actionResult2,
ActionResult3 = actionResult3
});
}
public void UpdateFeedFromController(string groupname, string itemId, Enums.FeedActivityTypes activityType,
string userId = "",
string actionResult1 = "",
string actionResult2 = "",
string actionResult3 = "")
{
_hubContext.Clients.Group(groupname).updateMessages(new FeedHubResponse
{
ItemId = itemId,
ActivityType = activityType.ToString(),
UserId = userId,
ActionResult1 = actionResult1,
ActionResult2 = actionResult2,
ActionResult3 = actionResult3
});
}
public void Join(string groupname)
{
Groups.Add(Context.ConnectionId, groupname);
}
}
public class FeedHubResponse
{
public string ItemId { get; set; }
public string UserId { get; set; }
public string ActionResult1 { get; set; }
public string ActionResult2 { get; set; }
public string ActionResult3 { get; set; }
public string ActivityType { get; set; }
public string Text { get; set; }
}

How to consume REST service using http POST

I defined a WCF implementation of REST service:
enter code here
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet(UriTemplate = "customers/{id}", ResponseFormat = WebMessageFormat.Json)]
Customer GetCustomer(string id);
[OperationContract]
[WebInvoke(UriTemplate = "customers", ResponseFormat = WebMessageFormat.Json)]
Customer PostCustomer(Customer c);
}
public class Service : IService
{
public Customer GetCustomer(string id)
{
return new Customer { ID = id, Name = "Demo User" };
}
public Customer PostCustomer(Customer c)
{
return new Customer { ID = c.ID, Name = "Hello, " + c.Name };
}
}
[DataContract(Namespace = "")]
public class Customer
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string Name { get; set; }
}
The Get operation is easy. Without proxy generation on the client side, I am not sure how to consume the POST service. Any code sample will be appreciated!
If you have the customer object on the client side also, you can use the Microsoft.Http libraries and do:
var client = new HttpClient()
var customer = new Customer() {ID=2, Name="Foo"};
var content = HttpContent.CreateJsonDataContract<Customer>(customer);
client.Post(new Uri("http://example.org/customers"),content);
if you want to avoid using a customer object, you can just build the JSON as a string and then create the content like this:
var content = HttpContent.Create("{...Json...}", "application/json");

Serializing Array of Objects to JSON in WCF to Comply with OpenSearch

I'm trying to write an OpenSearch Suggestion service that complies with the OpenSearch spec.
http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions
This spec requires the service to return a JSON array with the first element being a string and the following elements being arrays of strings. I'm able to get it almost there by returning an array of strings (string[][]) and having WCF serialize this into JSON. However, in order to comply with the spec, I tried to return an array of objects (object[]), with the first one being a string, and the rest being arrays of strings (string[]).
Whenever I try to return the array of objects, it doesn't work, such as this:
From service:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SuggestionService : ISuggestionService
{
public object[] Search(string searchTerms)
{
SearchSuggestions = new object[4];
SearchText = searchTerms;
SearchSuggestions[0] = SearchText;
Text = new string[10];
Urls = new string[10];
Descriptions = new string[10];
// Removed irrelevant ADO.NET code
while (searchResultReader.Read() && index < 10)
{
Text[index] = searchResultReader["Company"].ToString();
Descriptions[index] = searchResultReader["Company"].ToString();
Urls[index] = "http://dev.localhost/Customers/EditCustomer.aspx?id=" +
searchResultReader["idCustomer"];
index++;
}
SearchSuggestions[1] = Text;
SearchSuggestions[2] = Descriptions;
SearchSuggestions[3] = Urls;
return SearchSuggestions;
}
[DataMember]
public string SearchText { get; set; }
[DataMember]
public string[] Text { get; set; }
[DataMember]
public string[] Descriptions { get; set; }
[DataMember]
public string[] Urls { get; set; }
[DataMember]
public object[] SearchSuggestions { get; set; }
}
Here's the entire interface:
[ServiceContract]
public interface ISuggestionService
{
[OperationContract]
[WebGet(UriTemplate = "/Search?q={searchTerms}",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json)]
object[] Search(string searchTerms);
}
This causes the service to return "Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error." This is the only error I've been able to get.
Am I not able to use an array of objects to store one string and three arrays? What else could I do in order to use WCF to return the proper JSON that complies with this spec?
EDIT: Added lots more of the code
You posted a bunch of [DataMember]'s. Please post the entire [DataContract]. Also show us the JSON returned when you return that DataContract.
A Data Contract should never include behavior. Try the following (I haven't had a chance to test it, and will need to fake up the data to do so):
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SuggestionService : ISuggestionService
{
public SearchResults Search(string searchTerms)
{
var results = new SearchResults
{
SearchText = searchTerms,
Text = new string[10],
Urls = new string[10],
Descriptions = new string[10]
};
// Removed irrelevant ADO.NET code
int index = 0;
while (searchResultReader.Read() && index < 10)
{
results.Text[index] = searchResultReader["Company"].ToString();
results.Descriptions[index] = searchResultReader["Company"].ToString();
results.Urls[index] = "http://dev.localhost/Customers/EditCustomer.aspx?id=" +
searchResultReader["idCustomer"];
index++;
}
return results;
}
}
[DataContract]
public class SearchResults
{
[DataMember]
public string SearchText { get; set; }
[DataMember]
public string[] Text { get; set; }
[DataMember]
public string[] Descriptions { get; set; }
[DataMember]
public string[] Urls { get; set; }
}
Ok, I read enough of that spec and of the JSON spec, to convince myself you really do need to return an array of objects, and not an instance of a class that contains an array of objects. Of course, that didn't quite work. Here's what you needed:
[ServiceContract]
[ServiceKnownType(typeof(string))]
[ServiceKnownType(typeof(string[]))]
public interface ISuggestionService
{
[OperationContract]
[WebGet(UriTemplate = "/Search?q={searchTerms}",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json)]
object[] Search(string searchTerms);
}
I just tried it, and it worked. Here's the JSON (indentation added):
[
"abc",
["Company1","Company2","Company3",...],
["Company1 Description","Company2 Description","Company3 Description",...],
["http:\/\/dev.localhost\/Customers\/EditCustomer.aspx?id=1",
"http:\/\/dev.localhost\/Customers\/EditCustomer.aspx?id=2",
"http:\/\/dev.localhost\/Customers\/EditCustomer.aspx?id=3",...]
]
This is a problem that had me stumped for a while as well - there's a complete end-to-end walkthrough of how to do this, including how to support both JSON and XML opensearch (including XML attribute serialization), with downloadable code, at "Building Labs – Writing an OpenSearch Suggestions provider in C# with WCF".

Resources