简体   繁体   English

为什么输入模型在asp.net核心操作中为空

[英]Why is Input Model null in asp.net core action

I am submitting an order to my API.我正在向我的 API 提交订单。

Normally, it works fine.通常,它工作正常。 But sometimes, the inputModel is null.但有时, inputModel 为空。

Why would this occur?为什么会出现这种情况?

public async Task<Order> NewAsync(OrderInput input)

The input model will be null in the controller when the InputModel does not match the actual parameters passed to it.当 InputModel 与传递给它的实际参数不匹配时,输入模型在控制器中将为空。

To be clear: the controller does not care if additional parameters are passed to it, it will simply ignore them.需要明确的是:控制器不关心是否向它传递了额外的参数,它会简单地忽略它们。

But if there is a "required" parameter, such as:但是如果有一个“必需”参数,比如:

public int TypeId{get;set;}

and this is not provided, then the entire input model will be null.如果没有提供,那么整个输入模型将为空。

If TypeId is truely optional, then make it nullable, and then the input model will just set it to null.如果 TypeId 真的是可选的,那么让它可以为空,然后输入模型将它设置为空。

public int? TypeId{get;set;} 

To summarize: the controller has been passed a null value for an InputModel for which the InputModel does not allow null.总结一下:控制器已为 InputModel 传递了一个 null 值,而 InputModel 不允许为 null。 The result is the entire inputModel will be null when it is processed.结果是整个 inputModel 在处理时将为空。

This can be frustrating as no exception is thrown, all you get is a null model.这可能会令人沮丧,因为没有抛出异常,你得到的只是一个空模型。

The fix is to compare the post parameters in the browser with the Model and find which parameters is null that should not be.解决方法是将浏览器中的 post 参数与模型进行比较,并找出哪些参数不应该为 null。 This happens to me far more often than I would care to admit, and each time, I have to stop and figure this out again, so I thought I would go ahead and post this here to remind myself next time.这种情况发生在我身上的频率比我愿意承认的要多得多,而且每一次,我都必须停下来再次弄清楚这一点,所以我想我会继续在这里张贴这个以提醒自己下次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM