Basically what I'm trying to do is edit an entity that's stored in my db. For that I have a little method that is trying to access a paramater that's defined with #PathParam. My problem is that it comes back as null. Here is my method:
#PUT
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response edit(#PathParam("id") Long id, #QueryParam("myParam") String name)
{
return Response.ok().build();
}
I`m using Postman to send the parameter to my server. My URL looks like this:
http://localhost:8080/myApplication/rest/users/1?myParam=test
How can I get the value from the parameter?
Try with
public Response edit(#PathParam("id") Long id, #QueryParam("myParam") String myParam) {
return Response.ok().build();
}
This will work. The query param and variable name will get auto bind if they are similar.
Related
Not MVC!
Hi all,
What am I doing wrong here...
Im trying to pass an integer value from the onPost method of a Razor Page(Scores/Create.cshtml) to the onGet method of another page(/Scores/Index.cshtml) however the value is not being preserved and I either get null or 0 when inspecting the id value in the onGet method depending on how I send the integer.
I know this works using routes as I do this on another page
<a asp-page="/Scores/Index" asp-route-id="#item.ElementId">Update scores</a>
I have tried passing the value from an entity property like in the code example below, from ViewData variable, also from a locally created integer and finally just passing an integer value itself. In all cases the value is correct in the OnPost but never gets to the onGet.
The OnPost
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.TScores.Add(TScores);
await _context.SaveChangesAsync();
return RedirectToPage("./Index","OnGet",TScores.ElementId);
}
The OnGet
public async Task OnGetAsync(int? id)
{
TElements telement = new TElements();
telement = _context.TElements.Where(a => a.ElementId == id).FirstOrDefault();
I have also tried it without setting the OnGet method name in the RedirecttoPage
I am expecting to get the value of id in the onGet to match TScores.ElementID passed from the onPost.
Thanks in advance
D
The parameter requires an object, specifically an anonymous object of route values; it doesn't know what to do with an int.
return RedirectToPage("./Index", new { id = TScores.ElementId });
This question already has answers here:
Where can you find model binding errors in ASP.NET Core MVC?
(2 answers)
Closed 4 years ago.
I am creating a web api that receives data in a POST request in form of a JSON object in the body.
The real DataObj has many more fields so I simplify it to the following to show a specific sample where parsing must fail:
public class DataObj
{
public int Value { get; set; }
}
[HttpPost]
public async Task<IActionResult> SubTables([FromBody] DataObj data)
{
if (data == null)
{
string parsingErrorDetails = "";
// ? how can I check which kind of parsing erros happend?
return BadRequest("Failed to parse JSON with error: " + parsingErrorDetails);
}
..
}
Typically if you post valid JSON data to the service (like { "value": 1 } it just works fine.
But in the above example a valid JSON body would also be one like { "value": 6123456789 } parsing fails because the value exceeds Int32.MaxValue.
In my case the body has an object with several fields which makes it complicated to analyze the problem if I just return 404 Bad Request.
My goal is that I want to be able to report this specific problem back to the caller so that the caller has an easier option to analyze the root cause of the call.
Best without loosing the option to use [FromBody].
Is there a way to query details why the data object was null as in the sample above so that I can report it back to the caller?
I would check values on the setter properties of DataObj, throwing an exception in case the value doesn't fit.
public class DataObj
{
private int myInt;
public int MyInt{
get{ return myInt;}
set
{
if (value > int.MaxValue)
throw new ArgumentException("Invalid value for MyInt");
myInt = value;
}
}
I'm implementing an ASP.NET 5 API where I have the following POST method:
[HttpPost("{id}")]
public void Post([FromBody]string value)
{
// Do something
)
For me to process the request, I need both the ID and the string value which will be in the body.
I realize that I can also put the ID in the body but I was wondering if there's a way for me to get the ID directly from the route data -- like in MVC 4/5 where I'd use the following syntax:
var id = (string)this.RouteData.Values["id"];
What's the best way for me to get the ID value in ASP.NET 5? Use the code above or some other way?
You can decorate your parameter with [FromRoute]:
[HttpPost("{id}")]
public void Post([FromRoute] string id, [FromBody] string value) {
// Do something
)
I have an ASP.NET MVC app. My views use Razor. At the top of my CSHTML file, I have the following:
#functions
{
public static HtmlString IsSelectedCss(string name)
{
string selected = ""; // Need to get value of "t" from query string
HtmlString attribute = new HtmlString("");
if (selectedTab.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
attribute = new HtmlString("class=\"active\"");
}
return attribute;
}
}
I need this function to examine the query string. Specifically, I need to get the value of the "t" query string parameter. My challenge is, I cannot seem to figure out how to get access to the QueryString in this function.
How do I get the value of a query string parameter in a Razor function?
Thanks!
The query string can be gotten from below.
HttpContext.Current.Request.QueryString["t"]
You need to make your function non-static, since the querystring is part of the request.
You can then write
HttpContext.Request.Query["t"]
You should really be doing this in the controller and pushing it through the model. But if you insist, you can simply use:
<%= Request["t"] %>
But why not read it in your controller?!
I'm trying to make a call to a database using RequestFactory with Hibernate/JPA, and I want to retrieve a list of entities with embedded entities returned as well. I know that the .with() method works for methods like .find(), but it doesn't seem to work with custom queries.
The current way I'm doing it is as follows:
I used a named query in the entity class for the query. (Primary Entity is Name, embedded entity is a Suffix entity called nameSuffix)
#NamedQueries({ #NamedQuery(name = "Query.name", query = "select * from NameTable") })
Then in the service class, the .list() method, which is what I'd like to call with RequestFactory, is as follows.
public List<Name> list() {
return emp.get().createNamedQuery("Query.name").getResultList();
}
Finally, this is how I make the call in my client side code:
NameRequest context = requestFactory.createNameRequest();
context.list().with("nameSuffix").fire(new Receiver<List<NameProxy>>(){
public void onSuccess(List<NameProxy> response) {
String suff = response.get(0).getNameSuffix().getText();
}
});
In the above code, it says that getNameSuffix() returns null, which would imply that .with("nameSuffix") does not work with the .list() call like it does with the standard .find() method.
Is there a way to build a call that would return a list of entities and their embedded entities using .with(), or do I need to do it another way? If I need to do it another way, has anyone figured out a good way of doing it?
I think you misunderstood what the method with() is thought for, unless you had a method getNameSuffix which returns the NameSuffixentity. This is what the documentation says about it:
When querying the server, RequestFactory does not automatically populate relations in the object graph. To do this, use the with() method on a request and specify the related property name as a String
So, what you have to pass to the method is a list of the name of the child entities you want to retrieve. I hope this example could be helpful:
class A {
String getS(){return "s-a"}
B getB(){return new B();}
}
class B {
String getS(){return "s-b";}
C getC(){return new C();}
}
class C {
String getS(){return "s-c";}
}
context.getA().fire(new Receiver<A>(){
public void onSuccess(A response) {
// return 's-a'
response.getS();
// trhows a NPE
response.getB().getS();
}
});
context.getA().with("b").fire(new Receiver<A>(){
public void onSuccess(A response) {
// return 's-a'
response.getS();
// return 's-b'
response.getB().getS();
// trhows a NPE
response.getB().getC().getS();
}
});
context.getA().with("b.c").fire(new Receiver<A>(){
public void onSuccess(A response) {
// return 's-a'
response.getS();
// return 's-b'
response.getB().getS();
// return 's-c'
response.getB().getC().getS();
}
});