I'm using ServiceStack and have the route like this:
[Route("/hello/{Name*}")]
So anything like /hello/some/parameters should be handled.
Swagger use the following url: /hello/{Name*} and no matter what value I provide for Name parameter I get the following message when I hit "Try it out button":
A potentially dangerous client value Request.Path retrieved from the client(*).
Note, I'm using the following ApiMember attribute:
[ApiMember(Name = "Params", DataType = "string", ParameterType = "path" , IsRequired = true)]
and still any text I input is overriden with * and I have the error as above.
Is there any workaround for this?
First, the error is occurring because the Swagger call is using the default value of {Name*} in the path/request. (*) is not allowed in the path of the URL.
By using the correct attributes in your ServiceStack class, you should be able to get a text box to enter your own value within the Swagger UI.
Something like below should get the text box to appear. See https://github.com/ServiceStack/ServiceStack.UseCases/tree/master/SwaggerHelloWorld for examples.
public class Hello {
[ApiMember(Name=”Name*”, Description = “Name Description”, ParameterType = “path”, DataType = “string”, IsRequired = true)]
public string Name {get; set; }
}
Related
I am using JHipster 3.3. In the generated "entity"-dialog.html, I noticed the tag jhi-alert-error element will display server validation error so for example if a field is mandatory as specified in entity JPA class like
#NotNull
private String name;
Then error message for that field will be returned after clicking the Submit button if value of the field is empty.
So questions:
How is jhi-alert-error implemented? I can't seem to see its implementation
I tried tweaking JPA annotation to make a field unique BUT this time no error message will be displayed in jhi-alert-error if I break the unique constraint by adding 2 records having the same value for the field,
E.g.
// note 'unique=true' below
#NotNull
#Column(name = "name", unique=true)
private String name;
or
#Table(name="Module", uniqueConstraints = #UniqueConstraint(columnNames = "Name"))
public Class Module implements Serializable { ...
So how would I go about implementing my own server side form validation so error messages will be displayed in jhi-alert-error when the unique constraint of a field is broken after clicking the Submit button?
Thanks in advance,
I'm using a slightly older version of jhipster (2.26), so there could be some differences in the code. To answer your first question the jhi-alert-error is a custom Angular directive, have a look at the alert.directive.js file and the jhAlertError directive (should appear after the jhAlert directive). The directive expects the httpResponse.data object to be the ErrorDTO server side object.
To add custom error messages, you need to return an ErrorDTO object and the directive will display the message. To do this you need to throw an exception and ensure that the spring AOP - ExceptionTranslator is configured to catch it. If you don't want to create new custom Exceptions, you can use the CustomParameterizedException:
#RequestMapping(value = "/pizzas",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<Pizza> create(#RequestBody Pizza pizza) throws URISyntaxException {
if(pizza.isDisgusting()){
throw new CustomParameterizedException("Sorry, your pizza recipe is horrible");
}
log.debug("REST request to save Pizza : {}", pizza);
if (pizza.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new pizza cannot already have an ID").body(null);
}
Pizza result = pizzaRepository.save(pizza);
return ResponseEntity.created(new URI("/api/pizzas/" + pizza.getId())).body(result);
}
I have a business requirement to only send permissioned properties in our response payload. For instance, our response DTO may have several properties, and one of them is SSN. If the user doesn't have permissions to view the SSN then I would never want it to be in the Json response. The second requirement is that we send null values if the client has permissions to view or change the property. Because of the second requirement setting the properties that the user cannot view to null will not work. I have to still return null values.
I have a solution that will work. I create an expandoObject by reflecting through my DTO and add only the properties that I need. This is working in my tests.
I have looked at implementing ITextSerializer. I could use that and wrap my response DTO in another object that would have a list of properties to skip. Then I could roll my own SerializeToString() and SerializeToStream(). I don't really see any other ways at this point. I can't use the JsConfig and make a SerializeFn because the properties to skip would change with each request.
So I think that implementing ITextSerializer is a good option. Are there any good examples of this getting implemented? I would really like to use all the hard work that was already done in the serializer and take advantage of the great performance. I think that in an ideal world I would just need to add a check in the WriteType.WriteProperties() to look and the property is one to write, but that is internal and really, most of them are so I can't really take advantage of them.
If someone has some insight please let me know! Maybe I am making the implementation of ITextSerialzer a lot harder that it really is?
Thanks!
Pull request #359 added the property "ExcludePropertyReference" to the JsConfig and the JsConfigScope. You can now exclude references in scope like I needed to.
I would be hesitant to write my own Serializer. I would try to find solutions that you can plug in into the existing ServiceStack code. That way you will have to worry less about updating dlls and breaking changes.
One potential solution would be decorating your properties with a Custom Attributes that you could reflect upon and obscure the property values. This could be done in the Service before Serialization even happens. This would still include values that they user does not have permission to see but I would argue that if you null those properties out they won't even be serialized by JSON anyways. If you keep all the properties the same they you will keep the benefits of strong typed DTOs.
Here is some hacky code I quickly came up with to demonstrate this. I would move this into a plugin and make the reflection faster with some sort of property caching but I think you will get the idea.
Hit the url twice using the following routes to see it in action.
/test?role
/test?role=Admin (hack to pretend to be an authenticated request)
[System.AttributeUsage(System.AttributeTargets.Property)]
public class SecureProperty : System.Attribute
{
public string Role {get;set;}
public SecureProperty(string role)
{
Role = role;
}
}
[Route("/test")]
public class Test : IReturn
{
public string Name { get; set; }
[SecureProperty("Admin")]
public string SSN { get; set; }
public string SSN2 { get; set; }
public string Role {get;set;}
}
public class TestService : Service
{
public object Get(Test request)
{
// hack to demo roles.
var usersCurrentRole = request.Role;
var props = typeof(Test).GetProperties()
.Where(
prop => ((SecureProperty[])prop
.GetCustomAttributes(typeof(SecureProperty), false))
.Any(att => att.Role != usersCurrentRole)
);
var t = new Test() {
Name = "Joe",
SSN = "123-45-6789",
SSN2 = "123-45-6789" };
foreach(var p in props) {
p.SetValue(t, "xxx-xx-xxxx", null);
}
return t;
}
}
Require().StartHost("http://localhost:8080/",
configurationBuilder: host => { });
I create this demo in ScriptCS. Check it out.
I had a Dto with the following route defined
[Route("/route/{Id}/{Status}")]
public class JustIdAndStatus : IReturn {
public long Id { get; set; }
public long Status { get; set; }
}
Then I invoke the service with something like
localhost:9040/route/1/100
or
localhost:9040/route/0/100
and everything goes well.
but when I use one of the service clients I got an exception if any of the values is 0 (default value for the long).
var client = new JsonServiceClient("http://127.0.0.1:9040");
var request = new JustIdAndStatus() {
Id = 0,
Status = 1
};
var response = client.Get(request);
the exception I get is
System.InvalidOperationException : None of the given rest routes matches 'JustIdAndStatus' request:
/route/{Id}/{Status}: Could not match following variables: Id
at ServiceStack.ServiceClient.Web.UrlExtensions.ToUrl(IReturn request, String httpMethod, String formatFallbackToPredefinedRoute) in UrlExtensions.cs: line 65
at ServiceStack.Common.Tests.UrlExtensionTests.Can_create_url_with_JustIdAndStatus(Int64 id, Int64 status) in UrlExtensionTests.cs: line 91
I tracked down the issue to this commit on the service stack repository
https://github.com/ServiceStack/ServiceStack/commit/b34a5906a265da19d916ea47ee80783bd866abcb
I notice that when I updated from ServiceStack 3.9.38 to 3.9.40 from nuget.
I want to know if this behavior is right, so I'm using the routes in a wrong way or maybe this is an issue and can be submited to the issue tracker on github.
also I make a test using the basic ones I found on ServiceStack.Commons source code
https://gist.github.com/anonymous/5216727
Thanks in advance!
I agree with you that what you describe should be expected behaviour where the property is specifically referenced in the route.
The commit you refer to was intended to suppress the use of default parameter values on routes where members were relegated to the query string. However, it also appears to have caused the issue you describe with explicit routes.
I am putting together a pull request to address the issue and add some tests to reflect the expected behaviour.
Am practising MVC4 validations and got some basic idea. But am not sure where the Error message comes from in my below code and how to override the message
My model:
[Required(ErrorMessage = "Contact number field is required.")]
public int ContactNumber { get; set; }
when i leave the field empty am getting
Contact number field is required
but when i type any string and submit am getting
The value 'string i typed' is not valid for ContactNumber
how to override my error message ?
Add this validation to your propery which matches for valid number. This way you can override it.
[Required(ErrorMessage = "Contact number field is required.")]
[RegularExpression(#"[0-9]*\.?[0-9]+", ErrorMessage = "Contact number must be a Number.")]
public int ContactNumber { get; set; }
The error message you added was in the "Required" attribute, so it only gets used when something fails the "Required" check, ie. when it is left blank. If you want a particular message for when it's not a number then you'll need to add an attribute to check for that too, and give it a custom error message. A regex should do it. As a nice side effect of this, you can also take the opportunity to do some more detailed checking here, like making sure it's actually in phone number format with the right number of digits and stuff, rather than just checking that the value is numeric.
I am using ajax jquery for return a string , i have a entangle , it is Concatenate string
I want concatenate :
string str = "";
str += "<td>"+"<%= Html.ActionLink('Edit', 'ProcessUpdate/' + s.ProductId, 'Stationery')%>"+" </td>";
but when i run application , this is result :
I want to run the program the following results
Edit
thank for all !
It looks your issue is the parameters you are passing to Html.ActionLink(). Your question has been answered
here. The "/" character in your second parameter is not valid since this parameter is the action name in MVC2+ or the controller name in MVC1.
Assuming Stationery is the controller and ProcessUpdate is the action on the controller, your code should look like this:
Html.ActionLink("Edit", "ProcessUpdate", "Stationery" new { Id = s.ProductId }, new { } )
And here is the signature for the action
public ActionResult ProcessUpdate(string id)
{
// Do something
}
Note the last parameter is for Html Attributes and is required for this overload of Html.ActionLink() to work properly.