.net 7 BadRequestObjectResult uses CamelCase Policy - json

I have configured the JsonSerializerOptions's PropertyNamingPolicy as null, OData all results gets as expected, but BadRequestObjectResult is still using camelcase policy.
builder.Services.AddControllers()
.AddJsonOptions(options => {
options.JsonSerializerOptions.PropertyNamingPolicy = null; // to don't change property names lowercase
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
})
protected ActionResult ValidationFailed()
{
var err = new ODataError
{
Message = "Validation error",
Details = ModelState.ToDictionary(
kvp => kvp.Key, //.ToCamelCase(),
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
).Select(e => new ODataErrorDetail() {
ErrorCode = e.Key,
Message = string.Join("\n", e.Value.ToArray())
}).ToList()
};
return new BadRequestObjectResult(err);
}
{
"error": {
"code": "",
"message": "Validation error",
"details": [
{
"code": "person.corpid",
"message": "Corpid field must be value"
}
]
}
}
I want to get all results without changed like following.
{
"Error": {
"Code": "",
"Message": "Validation error",
"Details": [
{
"Code": "Person.Corpid",
"Message": "Corpid field must be value"
}
]
}
}

Related

how to login with rest api in flutter

i am new on json and flutter intergration, i have this login page , but when i click login it print failed and no token shown, i dont know where i get it wrong.
void login() async {
try{
Response response = await post(
Uri.parse('https://f2k/api/login'),
body: {
'email' : 'mimi#xyz.com',
'password' : '12345'
}
);
if(response.statusCode == 200){
var data = jsonDecode(response.body.toString());
print(data['token']);
print('Login successfully');
}else {
print('failed');
}
}catch(e){
print(e.toString());
}
}
json format for login
{
"email": "ddf#gmail.com",
"password": "password#123"
}
this is the results json after login
{
"status": "Request is successful",
"message": null,
"data": {
"user": {
"id": "101",
"attributes": {
"name": "DDF",
"email": "ddf#gmail.com",
"emailVerifiedAt": null,
"phone": "06xxxxxxxx",
"createdAt": "2023-01-23T11:15:41.000000Z",
"updatedAt": "2023-01-23T11:15:41.000000Z"
}
},
"token": "3|X0xxxxxxxxxxxxxxxxxx"
}
}

How to throw custom error from Velocity template using lambda

In my Lambda I am throwing custom error but from the vtl I am unable to get that when testing in Postman. In the postman I am keep getting message "A custom error was thrown from a mapping template." but I am expecting to get message and object from the custom class like source and errors
Here is my lambda function and custom error file
Custom Error file
export class ApiError extends Error {
source: string
args: string | undefined
errors: [{[key: string]: string | {[key: string]: string}}] | null | string
constructor(source: string, methodArgs: string, errors: [{[key: string]: string | {[key: string]: string}}] | null | string ) {
super();
this.source = source
this.args = methodArgs
this.errors = errors
}
}
export const completeProcess: Handler = async (event: any): Promise<CustomResponse> => {
const { customerId } = event.arguments.request as CustomRequest
if (customerId === null) {
throw new ApiError("completeProcess", JSON.stringify(event.arguments.request), "customerId missing")
}
}
Vtl file
request.vtl
{
"version": "2018-05-29",
"operation": "Invoke",
"payload": {
"field": "getError",
"arguments": $utils.toJson($context.arguments)
}
}
response.vtl
#if($context.error)
$utils.error($context.result.source, $context.result.errors)
#else
$utils.toJson($context.result)
#end
When running with above files I am keep getting response as
{
"data": {
"completeProcess": null
},
"errors": [
{
"path": [
"completeProcess"
],
"data": null,
"errorType": null,
"errorInfo": null,
"locations": [
{
"line": 2,
"column": 2,
"sourceName": null
}
],
"message": "A custom error was thrown from a mapping template."
}
]
}

Flutter and Json Retrieve a Title where value is

I have a Json array that is from wordpress. It retrives posts.
Each post has a serie of custom_options.
here an example:
{
"options":{
"wpcf-fields-select-option-f1d645c9017cce89714ede343df0cc73-1":{
"title":"-Select-",
"value":""
},
"wpcf-fields-select-option-3e64c784ce30a384e5167d1d6c1feb4e-1":{
"title":"1\/5",
"value":"S14"
},
"wpcf-fields-select-option-48334e061de93e6c47cc42c0fb5cd180-1":{
"title":"1\/8",
"value":"S1"
},
"wpcf-fields-select-option-a061ee2d2d302c5f42b2c93f9e811cdc-1":{
"title":"1\/12",
"value":"S2"
}
}
}
What I am trying to do is to call a function that will return the title of a given value.
Already tried using
// infoList is the json object
// resultVal is the value I am searching for
String getarrayinfos (infoList, resultVal) {
var result;
Map thisList = infoList;
for(var eachArr in thisList.keys){
if(thisList[eachArr]["value"] == resultVal){
result = thisList[eachArr]["title"];
}
}
return result.toString();
}
and printing it as the child of a container
// options is the json Object
// S7 is the value I am searching for
child: Text(getarrayinfos(options, "S7")),
but it prints the following error
flutter: type 'String' is not a subtype of type 'int' of 'index'
What am I doing wrong?
Instead of looking in infoList.keys look into infoList.values:
String getArrayInfo(Map theMap, String searchText) {
for (var val in theMap['options'].values) {
if (val['value'] == searchText) return (val['title']);
}
return 'not found';
}
void main() {
Map myMap = {
"options": {
"wpcf-fields-select-option-f1d645c9017cce89714ede343df0cc73-1": {
"title": "-Select-",
"value": ""
},
"wpcf-fields-select-option-3e64c784ce30a384e5167d1d6c1feb4e-1": {
"title": "1\/5",
"value": "S14"
},
"wpcf-fields-select-option-48334e061de93e6c47cc42c0fb5cd180-1": {
"title": "1\/8",
"value": "S1"
},
"wpcf-fields-select-option-a061ee2d2d302c5f42b2c93f9e811cdc-1": {
"title": "1\/12",
"value": "S2"
}
}
};
print(getArrayInfo(myMap, "S14"));
}

How to get key from Observable?

I am trying to read data from firebase using angular 2 and typescript
my code
export class DashboardComponent implements OnInit {
itemsRef: AngularFireList<any>;
items: Observable<any[]>;
constructor( afDatabase: AngularFireDatabase) {
this.itemsRef = afDatabase.list('/user_orders/louro');
this.items = this.itemsRef.valueChanges();
this.items.subscribe(val_2 => {
alert(val_2.keys());
val_2.forEach(function (value2) {
{
Object.keys(value2).forEach(function(k2) {
{
// k is key
let count = Object.keys( (value2[k2] )).length;
console.log("New order key "+k2);
for(let i=0;i<count;i++){
console.log(i+"=> "+JSON.stringify (value2[k2][i]));
}
}
});
}
})
});
}
ngOnInit() {
}
}
and on val_2 only contains
[
{
"-L7rtl2NesdOYVD4-bMs": [
{
"ads_show": false,
"brand": "",
"buttonLabel": "Add to cart",
"child": "fruits",
"decrn": "testing for demonstrate",
"key": "-L7rtXc0pMQhi1ClK-pP",
"mid": "fresh fruits",
"note": "",
"orderInfo": {
"message": "nil",
"methode": "cash on delivery",
"status": "nil",
"time": 1521356314040,
"time2": 1521356254115
},
"p_id": 73,
"p_name": "testing",
"position": 0,
"primary_key": "testinglouro",
"qty": {
"m_qty": 1,
"qty": 23,
"unite": "1kg",
"user_intput_qty": 2
},
"quantity_new": 2,
"querykey_shop_name_top": "louro_fruits",
"sellerName": "louro",
"sellonline": true,
"seo": {
"meta_descrption": "",
"meta_title": ""
},
"service": false,
"serviceMessage": "Please enter your complaint details",
"serviceTitle": "Service Requesting",
"shopname": "louro",
"shopview": false,
"summery": "nil",
"tags": "",
"top": "fruits",
"uid": "IG2SxH6Gcabr3QVLz9jE9Wwweh62",
"variants": [
{
"img_position": 0,
"prize": {
"mrp": 58,
"selling_prize": 45,
"tax": 0
},
"qty": {
"m_qty": 1,
"qty": 23,
"unite": "1kg",
"user_intput_qty": 2
},
"shipping": {
"minmumbuy": 0,
"s_cost": 0,
"s_dlts": ""
}
}
],
"variants_position": 0
}
]
}
]
And my database is
I need this key "4X2NpohlbUa3AA7ri6iHGNm2If93" .How to get that key ? I tried val_2.key
but it showing error "[ts] Property 'key' does not exist on type 'any[]'. Did you mean 'keys'?"
In java i am using below code and work fine dataSnapshot1.getKey();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(getResources().getString(R.string.user_orders)+"/"+
shop_name,getContext()));
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// MainAction.setDefaults("OpenCategories",dataSnapshot.toString(),getActivity());
if (dataSnapshot.hasChildren()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
orderDetails1 = null;
orderDetails1 = new OrderDetails();
if (dataSnapshot1.hasChildren()) {
int id = -1;
for (DataSnapshot dataSnapshot2 : dataSnapshot1.getChildren()) {
id = id + 1;
if (dataSnapshot2.hasChildren()) {
int productid = -1;
for (DataSnapshot dataSnapshot3 : dataSnapshot2.getChildren()) {
productid = productid + 1;
if (dataSnapshot3.hasChildren()) {
orderDetails1.productmillaList.add(dataSnapshot3.getValue(Productmilla.class));
}
orderDetails1.productmillaList.get(productid).setPosition(Integer.parseInt(dataSnapshot3.getKey()));
orderDetails1.productmillaList.get(productid).setId(dataSnapshot2.getKey());
// Log.d("key2",dataSnapshot2.getKey()+" "+productid);
}
}
//orderDetails1.productmillaList.get(id).setId(dataSnapshot2.getKey());
}
}
orderDetails1.key = dataSnapshot1.getKey();
orderDetails.add(orderDetails1);
}
getaddress(orderDetails);
} else mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
mProgressBar.setVisibility(View.GONE);
Log.w("dd", "Failed to read value."+ error.getMessage());
}
});
Update :
According to the updated response data, you should access using Object.keys(val)[0] which gives the value for key "4X2NpohlbUa3AA7ri6iHGNm2If93", since it is the first key.
According to older response data :
Your val is an array.
This should work.
Object.keys(val[0]).forEach(function(k1) {
{
console.log("Key first : "+ k1);
});
In your JSON, val is an array.
Object.keys(val[0])
will give you the keys of the first element of that array, which is what you're after.
TO get the first key in the Object
Object.keys(val)[0]; //returns 'first key'
[https://stackoverflow.com/a/11509718/7458082][1]
To iterate through the object
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
[https://stackoverflow.com/a/11509718/7458082][1]

How to remove Task json properties in Nancy.Response.AsJson

I've made one of my API endpoints and inner logic asynchronous and when previously I've used Response.AsJson(Foo.bar()) , it would return the json representation normally, but now I see this appended to it:
{
"result": [
{
"id": "59d680cc734d1d08b4e6c89c",
"properties": {
"name": "value"
}
}
],
"id": 3,
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false
}
But I want it to be like this:
"id": "59d680cc734d1d08b4e6c89c",
"properties": {
"name": "value"
}
As I understand, it's because I've wrapped my object in a Task , but I can't figure out, how with Nancy framework, which I use the Response.AsJson, to make it so the properties are excluded. I can obviously omit the Response.AsJson of the returned object, but then response is no longer Json if requesting through web-browser for example.
For further example
NancyModule for routing API:
public ItemCatalogModule(IItemCatalog itemCatalog) : base("/itemCatalog")
{
Get("/fetch/{id}", async parameters =>
{
var id = (string) parameters.id;
var response = await Response.AsJson(itemCatalog.GetItem(id));
return response;
});
}
How the interface looks like of ItemCatalog:
public interface IItemCatalog
{
Task<Item> GetItem(string id);
}
You shoud do this :
public ItemCatalogModule(IItemCatalog itemCatalog) : base("/itemCatalog")
{
Get("/fetch/{id}", async parameters =>
{
var id = (string) parameters.id;
return Response.AsJson(await itemCatalog.GetItem(id));
});
}