How to set ASP.NET Web Api Route Constraint HTTP Status Return Code - asp.net-web-api

I am using ASP.NET Web Api 2 framework and using a basic route constraint as below.
[Route("Number/{id:int:min(2):max(10)}")]
public HttpResponseMessage GetNumber([FromUri] int id)
{
return (id > 0)
? Request.CreateResponse(HttpStatusCode.OK, id)
: Request.CreateResponse(HttpStatusCode.PreconditionFailed);
}
I would like to know when the id is conflict with the constraint above, .e.g. 1 or 11,
how can I overrride the default HTTP Status Return code which is 404?
Thanks very much.

You can create a custom route constraint that will check the min, max values like you wish, and additionally allow you to specify the HttpStatusCode in case the constraint is not fulfilled correctly.
public class RangeWithStatusRouteConstraint : IHttpRouteConstraint
{
private readonly int _from;
private readonly int _to;
private readonly HttpStatusCode _statusCode;
public RangeWithStatusRouteConstraint(int from, int to, string statusCode)
{
_from = from;
_to = to;
if (!Enum.TryParse(statusCode, true, out _statusCode))
{
_statusCode = HttpStatusCode.NotFound;
}
}
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values,
HttpRouteDirection routeDirection)
{
object value;
if (values.TryGetValue(parameterName, out value) && value != null)
{
var stringValue = value as string;
var intValue = 0;
if (stringValue != null && int.TryParse(stringValue, out intValue))
{
if (intValue >= _from && intValue <= _to)
{
return true;
}
//only throw if we had the expected type of value
//but it fell out of range
throw new HttpResponseException(_statusCode);
}
}
return false;
}
}
Now you need to register it in the attribute mapping:
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("rangeWithStatus", typeof(RangeWithStatusRouteConstraint));
config.MapHttpAttributeRoutes(constraintResolver);
And your route can now look like this:
public class MyController : ApiController
{
[Route("Number/{id:int:rangeWithStatus(2, 10, PreconditionFailed)}")]
public HttpResponseMessage GetNumber([FromUri] int id)
{
return Request.CreateResponse(HttpStatusCode.OK, id);
}
}
in this case Conflict is a string representation of HttpStatusCode.Conflict enumeration, which is later cast to the enum value in the constraint.
With such setup, if the value falls out of the [2, 10] range, the Web API infrastructure will respond with 409 status code instead of the default 404.

Remove the constraint on the route, and do the validation inside the method.
Constraints are used to figure out if a route should be used at all, but you want to use the route to be hit but change the status code if the input falls outside some parameters.
[Route("Number/{id})] // No constraints
public HttpResponseMessage GetNumber([FromUri] int id)
{
return (id > 1 && id < 11) // here you validate id range
? Request.CreateResponse(HttpStatusCode.OK, id)
: Request.CreateResponse(HttpStatusCode.PreconditionFailed);
}

I think that the correct solution is to check constraint inside controller (as #aanund suggested). However if you want to keep the Route constraints and avoid conditionals in your code, you may create another action controller with the same route but without constraints. If the constraints are not verified the new action controller will be called:
[Route("Number/{id:int:min(2):max(10)}")]
public HttpResponseMessage GetNumber([FromUri] int id)
{
Request.CreateResponse(HttpStatusCode.OK, id)
}
[Route("Number/{id}")]
public HttpResponseMessage GetNumber2([FromUri] int id)
{
Request.CreateResponse(HttpStatusCode.PreconditionFailed);
}

Related

ASP.NET WebApi2 OData handling of queries with slash /

I have made a "standard" Web Api 2 OData project with convention model routing. Following OData queries are working:
/odata/Users
/odata/Users(123)
/odata/$metadata
/odata/Users?$select=Username
So everything seemed to be fine until I tried this, which I think is also a legal OData query:
/odata/Users(123)/Username
Slash / in query breaks everything and it does not hit the controller class and OData authentication flow at all. Should this be supported at all in Microsoft ASP.NET OData implementation? Or is this supported only if I define explicit methods with correct routes for every single property like Username? Any suggestions to fix this? I have tried explicit {*rest} routes etc.
AFAIK, the built-in routing conventions don't include one for property access. You'd be required to add many actions for every property access.
However, based on this resource here, it's not all that difficult to add a custom routing convention to handle the property access path template: ~/entityset/key/property
Here's a custom routing convention adapted from the link I shared above
Assembly used: Microsoft.AspNet.OData 7.4.1 - the approach would be the same for any other OData Web API library you might be using
Class used for illustration
public class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
Add routing convention for property access
// Usings
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNet.OData.Routing.Conventions;
using System;
using System.Linq;
using System.Web.Http.Controllers;
// ...
public class CustomPropertyRoutingConvention : NavigationSourceRoutingConvention
{
private const string ActionName = "GetProperty";
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (odataPath == null || controllerContext == null || actionMap == null)
{
return null;
}
if (odataPath.PathTemplate == "~/entityset/key/property" ||
odataPath.PathTemplate == "~/entityset/key/cast/property" ||
odataPath.PathTemplate == "~/singleton/property" ||
odataPath.PathTemplate == "~/singleton/cast/property")
{
var segment = odataPath.Segments.OfType<Microsoft.OData.UriParser.PropertySegment>().LastOrDefault();
if (segment != null)
{
string actionName = FindMatchingAction(actionMap, ActionName);
if (actionName != null)
{
if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
{
var keySegment = odataPath.Segments.OfType<Microsoft.OData.UriParser.KeySegment>().FirstOrDefault();
if (keySegment == null || !keySegment.Keys.Any())
throw new InvalidOperationException("This link does not contain a key.");
controllerContext.RouteData.Values[ODataRouteConstants.Key] = keySegment.Keys.First().Value;
}
controllerContext.RouteData.Values["propertyName"] = segment.Property.Name;
return actionName;
}
}
}
return null;
}
public static string FindMatchingAction(ILookup<string, HttpActionDescriptor> actionMap, params string[] targetActionNames)
{
foreach (string targetActionName in targetActionNames)
{
if (actionMap.Contains(targetActionName))
{
return targetActionName;
}
}
return null;
}
}
Add single method in your controller to handle request for any property
public class ProductsController : ODataController
{
// ...
[HttpGet]
public IHttpActionResult GetProperty(int key, string propertyName)
{
var product = _db.Products.FirstOrDefault(d => d.Id.Equals(key));
if (product == null)
{
return NotFound();
}
PropertyInfo info = typeof(Product).GetProperty(propertyName);
object value = info.GetValue(product);
return Ok(value, value.GetType());
}
private IHttpActionResult Ok(object content, Type type)
{
var resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
}
// ...
}
In your WebApiConfig.cs (or equivalent place where you configure the service)
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Product>("Products");
var routingConventions = ODataRoutingConventions.CreateDefaultWithAttributeRouting("odata", configuration);
routingConventions.Insert(0, new CustomPropertyRoutingConvention());
configuration.MapODataServiceRoute("odata", "odata", modelBuilder.GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
configuration.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
configuration.EnsureInitialized();
Request for Name property: /Products(1)/Name
Request for Id property: /Products(1)/Id

spring mvc checking checkbox does not set object

Hi I am new to spring MVC and am trying to implement a form:checkboxes tag and have run into a few issues. All the examples I have googled work with Strings and i want to work with objects so am hoping someone can advise.
I have a List of objects set in my DTO as follows:
TestDTO
private List<Barrier> barriers;
public List<Barrier> getBarriers() {
return barriers;
}
public void setBarriers(List<Barrier> barriers) {
this.barriers = barriers;
}
in my controller class I fetch the barrier objects from the database and add them to my DTO which will be passed to the jsp
savedRecord.setBarriers(dataService.getBarriers());
mav.addObject("testDto", savedRecord);
in my JSP I use the form:checkboxes tag as follows:
<form:checkboxes path="barriers" items="${testDto.barriers}" element="label class='block-label'"
itemLabel="barrier"/>
I also tried with adding
itemValue="id"
but that did not work either
this is wraped in a from element
<form:form method="post" accept-charset="UTF-8" action="${action}"
onsubmit="return checkAndSend()" id="create"
novalidate="" modelAttribute="testDto">
So the issues I am having are as follows:
The checkboxes when displayed all seem to be checked. I have implemented a hashcode and equals method on the barrier object but they still all seem to be checked when I want them unchecked.
Barrier.java
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((barrier == null) ? 0 : barrier.hashCode());
result = prime * result + ((display == null) ? 0 : display.hashCode());
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Barrier other = (Barrier) obj;
if (barrier == null) {
if (other.barrier != null)
return false;
} else if (!barrier.equals(other.barrier))
return false;
if (display == null) {
if (other.display != null)
return false;
} else if (!display.equals(other.display))
return false;
if (id != other.id)
return false;
return true;
}
When I click submit and i look at the testDto my barriers object list is null. How do I get the checked boxes that represent objects to be set on my testDto.
Any pointers and advice is appreciated
Thanks
UPDATE:
Thanks for the pointers. I went with the following. your suggestion helped.
I created the folloiwng in my controller
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Barrier.class, new BarrierPropertyEditor(barrierService));
}
and then added a class to do the conversion
public class BarrierPropertyEditor extends PropertyEditorSupport {
private BarrierService barrierService;
public BarrierPropertyEditor(BarrierService barrierService) {
this.barrierService = barrierService;
}
#Override
public void setAsText(String text) {
Barrier b = barrierService.findById(Integer.valueOf(text));
setValue(b);
}
}
This sets the barrier objects on my DTO.
(Sorry for the caps) IT DOES NOT SOLVE WHY THE CHECKBOXES ARE CHECKED ON INITIAL LOAD.
Any ideas how to set the checkboxes unchecked on intitial load?
You can use #ModelAttribute in your Controller to provide the list of values in checkboxes.
#ModelAttribute("barrierList")
public List<Barrier> populateBarrierList() {
List<Barrier> barrierList = dataService.getBarriers();
for(Barrier barrier: barrierList )
{
barrierList.add(barrier);
}
return barrierList ;
}
In JSP, use following :
<form:checkboxes path="barriers" items="${barrierList}" element="label class='block-label'" itemLabel="barrier"/>

Trying to save comma-separated list

Trying to save selections from a CheckBoxList as a comma-separated list (string) in DB (one or more choices selected). I am using a proxy in order to save as a string because otherwise I'd have to create separate tables in the DB for a relation - the work is not worth it for this simple scenario and I was hoping that I could just convert it to a string and avoid that.
The CheckBoxList uses an enum for it's choices:
public enum Selection
{
Selection1,
Selection2,
Selection3
}
Not to be convoluted, but I use [Display(Name="Choice 1")] and an extension class to display something friendly on the UI. Not sure if I can save that string instead of just the enum, although I think if I save as enum it's not a big deal for me to "display" the friendly string on UI on some confirmation page.
This is the "Record" class that saves a string in the DB:
public virtual string MyCheckBox { get; set; }
This is the "Proxy", which is some sample I found but not directly dealing with enum, and which uses IEnumerable<string> (or should it be IEnumerable<Selection>?):
public IEnumerable<string> MyCheckBox
{
get
{
if (String.IsNullOrWhiteSpace(Record.MyCheckBox)) return new string[] { };
return Record
.MyCheckBox
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(r => r.Trim())
.Where(r => !String.IsNullOrEmpty(r));
}
set
{
Record.MyCheckBox = value == null ? null : String.Join(",", value);
}
}
To save in the DB, I am trying to do this in a create class:
proxy.MyCheckBox = record.MyCheckBox; //getting error here
but am getting the error:
Cannot implicitly convert 'string' to System.Collections.Generic.IEnumerable'
I don't know, if it's possible or better, to use Parse or ToString from the API for enum values.
I know that doing something like this will store whatever I put in the ("") into the DB, so it's just a matter of figuring out how to overcome the error (or, if there is an alternative):
proxy.MyCheckBox = new[] {"foo", "bar"};
I am not good with this stuff and have just been digging and digging to come up with a solution. Any help is much appreciated.
You can accomplish this using a custom user type. The example below uses an ISet<string> on the class and stores the values as a delimited string.
[Serializable]
public class CommaDelimitedSet : IUserType
{
const string delimiter = ",";
#region IUserType Members
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y))
{
return true;
}
var xSet = x as ISet<string>;
var ySet = y as ISet<string>;
if (xSet == null || ySet == null)
{
return false;
}
// compare set contents
return xSet.Except(ySet).Count() == 0 && ySet.Except(xSet).Count() == 0;
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var outValue = NHibernateUtil.String.NullSafeGet(rs, names[0]) as string;
if (string.IsNullOrEmpty(outValue))
{
return new HashSet<string>();
}
else
{
var splitArray = outValue.Split(new[] {Delimiter}, StringSplitOptions.RemoveEmptyEntries);
return new HashSet<string>(splitArray);
}
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var inValue = value as ISet<string>;
object setValue = inValue == null ? null : string.Join(Delimiter, inValue);
NHibernateUtil.String.NullSafeSet(cmd, setValue, index);
}
public object DeepCopy(object value)
{
// return new ISet so that Equals can work
// see http://www.mail-archive.com/nhusers#googlegroups.com/msg11054.html
var set = value as ISet<string>;
if (set == null)
{
return null;
}
return new HashSet<string>(set);
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public SqlType[] SqlTypes
{
get { return new[] {new SqlType(DbType.String)}; }
}
public Type ReturnedType
{
get { return typeof(ISet<string>); }
}
public bool IsMutable
{
get { return false; }
}
#endregion
}
Usage in mapping file:
Map(x => x.CheckboxValues.CustomType<CommaDelimitedSet>();

No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments

I want to retrieve a specific record using IQueryable. But i get error 'No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.'. I got the selected row id, but I cannot display it out. Here is my code.
internal static IQueryable GetRecordsFromPrimaryKeys(this IQueryable datasource, List<FilterDescriptor> primaryKeys)
{
IQueryable data = datasource;
ParameterExpression paramExp = null;
bool firstLoop = false;
System.Linq.Expressions.Expression predicate = null;
var RecordType = datasource.GetObjectType();
paramExp = RecordType.Parameter();
foreach (FilterDescriptor primaryKey in primaryKeys)
{
if (!(firstLoop))
{
predicate = data.Predicate(paramExp, primaryKey.ColumnName, primaryKey.Value, FilterType.Equals, false, RecordType);
firstLoop = true;
}
else
{
predicate = predicate.AndPredicate(data.Predicate(paramExp, primaryKey.ColumnName, primaryKey.Value, FilterType.Equals, false, RecordType));
}
}
if (paramExp != null && predicate != null)
{
var lambda = Expression.Lambda(predicate, paramExp);
data = data.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"Where",
new Type[] { data.ElementType },
data.Expression,
lambda
)
);
}
return data;
}
My Code works well for IEnumerable/IQueryable/ICollection . But it throws the exception when i specify the class with the keyword virtual and type as ICollection. My code is
public class RoomType
{
public int ID { get; set; }
[MaxLength(10, ErrorMessage = "Room code cannot be longer than 10 characters.")]
public string Code { get; set; }
[MaxLength(50, ErrorMessage = "Room name cannot be longer than 50 characters.")]
public string Name { get; set; }
public virtual ICollection<RoomCategory> RoomCategories { get; set; }
}
Some random values gets appended to 'RecordType' while using the keyword 'virtual'. I think this leads to the exception. Still searching for the solution.
I don't know what is going wrong . Any suggestions welcome.
Thanks.
I just ran into a similar situation. The problem stems from the fact that in some cases you're dealing with the "proxy" not the actual entity. So, you want to make sure that RecordType matches data.ElementType.
try:
var recordType = datasource.GetObjectType();
// make sure we have the correct type (not the proxy)
if (recordType.BaseType.Name != "Object")
recordType = recordType.BaseType;
Or better yet, try:
var recordType = data.ElementType
Try to use typeof(Enumerable) instead of typeof(Queryable)

How do I load an entity from a database where the Composite ID of the record contains a key-property with a null value?

I am reading data from an external organisation using Oracle.DataAccess through the Oracle10g provider. One of the tables has a composite id made up of these fields.
course:
institutioncode: "X11"
coursecode: "N100"
campuscode: "A"
entryyear: 2011
entrymonth: 10
The problem is that the campus code is allowed to be null by the external provider instead of empty. This leads to nHibernate returning collections that contain null references instead of course entities.
Other domain objects will use these fields to refer to this course entity as well, so this is actually used as a key and I can't easily remap to use a surrogate key.
From the source in tag 3.1.0GA, the check that is causing this behavior can be found in Nhibernate.Type.ComponentType.Hydrate(IDataReader rs, string[] names, ISessionImplementor session, object owner). This is always refusing the possibility that a key-property could be null. Could this change to make nullability an option on key-property and key-reference properties?
Failing that, how would you recommend reading this data directly with nHibernate?
NULL values in properties are not supported by design.
There are two ways to deal with this:
Import the data instead of using it raw from the source, adding a proper surrogate key.
Handle that entity without NHibernate.
ok my first comment didnt worked out on References (ManyToOne). So here my alternative solution: a usertype to work around the check.
class CourseMap : ClassMap<Course>
{
public CourseMap()
{
CompositeId()
.KeyProperty(c => c.InstitutionCode)
.KeyProperty(c => c.CourseCode)
.KeyProperty(c => c.CampusCode, key => key.Type(typeof(MyUserType)))
.KeyProperty(c => c.EntryYear)
.KeyProperty(c => c.EntryMonth);
}
}
class MyUserType : IUserType
{
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object DeepCopy(object value)
{
return value;
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public new bool Equals(object x, object y)
{
return object.Equals(x, y);
}
public int GetHashCode(object x)
{
return (x == null) ? 0 : x.GetHashCode();
}
public bool IsMutable
{
get { return false; }
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var value = NHibernateUtil.String.NullSafeGet(rs, names[0]);
return (value == null) ? string.Empty : value;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
string d = string.IsNullOrEmpty((string)value) ? null : (string)value;
NHibernateUtil.String.NullSafeSet(cmd, d, index);
}
public object Replace(object original, object target, object owner)
{
return DeepCopy(original);
}
public Type ReturnedType
{
get { return typeof(string); }
}
public SqlType[] SqlTypes
{
get { return new[] { SqlTypeFactory.GetString(100) }; }
}
}
class SomeEntityMap : ClassMap<SomeEntity>
{
public EntityMap()
{
Id(e => e.Id).GeneratedBy.Assigned();
References(e => e.Course)
.Columns("InstitutionCode", "CourseCode", "CampusCode", "EntryYear", "EntryMonth")
.Fetch.Join(); // important because we can't rely on values, NULL is invalid value
}
}

Resources