如何阻止ASP.NET在GET Action方法中注入对象



我有一个用参数调用的操作方法,其中一个参数是int并且动作方法的另一个参数是CCD_ 2。

当我检查动作方法时,我看到CCD_,该对象的UserId属性设置为值e.g. model.UserId = 82

如何阻止ASP.NET创建对象?我可以通过将userId基元变量重命名为paramUserId来破解这个问题,但并不理想。

这里是操作方法:

[HttpGet]
public async Task<IActionResult> Select(int userId = 0, ObjectModel model = null)

网址:

https://localhost:5001/[Area]/[Controller]/Select?userId=82

对象模型:

public class ObjectModel
{
public int Id { get; set; }
public int UserId { get; set; }
}

get请求中的复杂模型是以querystring的格式传递的,因此当您调用https://localhost:5001/[Area]/[Controller]/Select?userId=82时,默认的模型绑定将自动匹配值绑定的参数(不区分大小写(。如果您不想更改int类型的参数名称,您可以尝试自定义模型绑定,该绑定基于请求中UserId的大小写来绑定模型,如下所示:

MyCustomerModelBinder

public class MyCustomerModelBinder:IModelBinder
{
public  Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelResult = new ObjectModel();
//Get the Query in the request 
var queryResult =new Dictionary<string, string>();
var query = bindingContext.HttpContext.Request.Query;
foreach (var k in query.Keys)
{
StringValues v = string.Empty;
var flag = query.TryGetValue(k, out v);
if (flag)
{
queryResult.Add(k, v);
}
}
// Bind model when UserId exists in the Query
if (queryResult.ContainsKey("UserId"))
{
modelResult.Id =Convert.ToInt32(bindingContext.ValueProvider.GetValue("id").FirstValue);
modelResult.UserId =Convert.ToInt32(bindingContext.ValueProvider.GetValue("UserId").FirstValue);
bindingContext.Result = ModelBindingResult.Success(modelResult);
return Task.CompletedTask;
}
modelResult = null;
bindingContext.Result = ModelBindingResult.Success(modelResult);
return Task.CompletedTask;
}
}

行动

[HttpGet]
public async Task<IActionResult> Select(int userId = 0, [ModelBinder(BinderType = typeof(MyCustomerModelBinder))] ObjectModel model = null)

最新更新