Home > Net >  Front to want me to handle, he came int type parameter null, but writing a custom binding model, can
Front to want me to handle, he came int type parameter null, but writing a custom binding model, can

Time:05-24

When I took over, the project already exists,

But at the same time with me to take over the front end, put forward the professional requirements,
Output should have unified format,
Want to have a swagger

But before the project is to use the.net Framework written Framework, not pure single webapi,

Helpless, I took him to upgrade to the latest. Net6 framework, basic can cope with the demand of the front end, but found a serious problem, before receiving parameters is very free, automatic binding is very high, such as defining the parameters of type int, front the null values, can also automatically restore to default value 0, but rises to. Net6 adopts the model of webapi, ineffective, redefined as int? Engineering is too big, to find the Internet a lot of data and Microsoft's official documents, add this BBS's enthusiastic help and answer, finally solved for me, wrote a custom rebind the data modeling methods, there is a hidden danger, but in the process of rebound, must know in advance the type of parameter itself, so I use swith, illustrates all types of my project for the reduction, and int [] of this type, haven't solve, I don't know how to restore, if we can remove front-end for null values of parameters, and use the method of automatically binding binding template form is perfect, but always can't find relevant syntax online, do not know to have a way to master, thank you,

 using the BLL; 
Using Microsoft. AspNetCore. Mvc. ModelBinding;
Using the Model.
Using Newtonsoft. Json;
Using Newtonsoft. Json. Linq;
Using System;
Using System. Collections. Generic;
Using System. IO;
Using System. The Runtime. Serialization. Json;
Using System. The Text;
Using System. The Threading. The Tasks;
The namespace ZFY_API. Filter
{
///& lt; Summary>
///this function is the parameters of the filter value is null
///& lt;/summary>
Public class UserModelBinder: IModelBinder
{
Public Task BindModelAsync (ModelBindingContext bindingContext)
{

JObject j=new JObject ();
//get the interface parameter type
Type Type=bindingContext. ModelMetadata. ModelType;
//define an interface type parameter
Var Data=https://bbs.csdn.net/topics/Activator.CreateInstance (Type);
//gain parameters, in the form of jobject save standby
The object C=new object ();
String bodyStr=string. The Empty;
Using (var reader=new StreamReader (bindingContext. HttpContext. Request. Body, Encoding, UTF8, true, 1024, true))
{
Var bodyRead=reader. ReadToEndAsync ();
J=JsonConvert DeserializeObject (bodyRead. Result);
}
JObject jParam=new JObject ();
The foreach (var rs in j)
{
If (rs. A null Value=https://bbs.csdn.net/topics/=)//exclude the transfer of null reference
{
JParam. Add (new JProperty (rs. Key, rs. Value));
}
}
//manually rebind data model
String obStr=jParam. ToString ();
C=JsonConvert. DeserializeObject (obStr);
IEnumerable The properties of=j. roperties ();
Foreach (System. Reflection. PropertyInfo info in the GetProperties ())
{
String Name=info. Name;
String type=info. PropertyType. Name. ToLower ();
The foreach (var rs in j)
{
If (rs) Value) ToStr (). The Length & gt; 0 & amp; & Name. ToLower ()==rs. Key. ToLower ())
{
The switch (type)
{
Case "int32" :
Info. SetValue (Data, rs (int). The Value).
break;
Case "decimal" :
Info. SetValue (Data, (decimal) rs. Value);
break;
Case "double" :
Info. SetValue (Data, (double) rs. Value);
break;
Case "byte" :
Info. SetValue (Data, rs (byte). The Value).
break;
Case "string" :
Info. SetValue (Data, rs (string). The Value).
break;
Case "Boolean" :
Info. SetValue (Data, (bool) rs. Value);
break;
Int32 case "[]" :
Info. SetValue (Data, GetObjectFromJsonbreak;
Case "string []" :
Info. SetValue (Data, rs. Value. The ToString (). The Split (', '));
break;
Default:
Info. SetValue (Data, GetObjectFromJsonbreak;
}
}
}
}




////automatic binding data model
//var model=bindingContext. Result. The model;
BindingContext. Result=ModelBindingResult. Success (Data);
Return to Task.Com pletedTask;
}

Public static T GetObjectFromJson (string jsonString, Type, Type)
{
Var dcSerializer=new DataContractJsonSerializer (type);
Using (var stream=new MemoryStream (Encoding UTF8. GetBytes (jsonString)))
{
Return (T) dcSerializer. ReadObject (stream);
}
}
}
}



To solve the problem is how to this line of code GetObjectFromJsonSuch as GetObjectFromJson
GetObjectFromJson
GetObjectFromJson
GetObjectFromJson
. .
Type, etc., like the simple, known well, but if
Especially the type of the custom, this is unknowable
This method doesn't work, so if to solve the deficiency of the mentioned, directly in the Startup injection is more simple

CodePudding user response:

Is I think too much, actually don't need to swith, direct the object class line

Info. SetValue (Data, GetObjectFromJson (rs. Value. The ToString (), info. PropertyType));

CodePudding user response:

Well, I say you the front end???

Oh, you are on a post said, "you dare pass null for him, he asked to you into an empty string, empty collection, empty object", and then the post said, "you can't give me a null, I can give you pass null, your own choice", "

Last post and I said, this art, you don't have to serve to serve, next his request is "I think this API is not good, I want to own splicing data, you should help me get the data together, I use easyui form, for example, you much trouble as a form, after you end the header, data, transform in the back-end press easyui datagrid are together how"

Ps: your request we generally can be configured in the "global serialization" default value, but the null and 0 is really different, at the same time for the front end of the condom so can't open, you want to the front end through couldn't speak rules, unreasonable hole, and at the back of the things, you really can't help

CodePudding user response:

 public void ConfigureServices (IServiceCollection services) 
{
//Add framework services.
Services. AddControllers (
//global configuration Json serialization handling
AddJsonOptions (options=& gt;
{
//we usually here for serialization and deserialization of global configuration

}
);
nullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnull
  •  Tags:  
  • C#
  • Related