控制器的方法(http get):可选参数不为null [英] Controller's method(http get): optional parameter is not null

查看:110
本文介绍了控制器的方法(http get):可选参数不为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Controller方法,可以选择接受ID和一个 ComplexObject .

I have simple Controller's method that accepts Id and a ComplexObject optionally.

我通过URL使用 id 参数输入此方法(下面是URL后面的代码),但是当我在该方法中设置断点时,则 optionalFormData 不为null,而是

FormData 实例,具有除以外的所有内容( FirstName SecondName File )> Id (Guid)为空.

I'm entering this method with id parameter via URL (below is code behind URL), but when I'm setting break point inside that method, then optionalFormData is not null, but instead it is FormData instance with everything (FirstName, SecondName, File) except Id (Guid) being null.

我希望 optionalFormData 在不发送时为空,而不是成为具有 null 个属性值的 FormData 的实例.

I want optionalFormData to be null when it is not sent instead of being an instance of FormData with null values of properties.

伪代码:

public IActionResult MyView(Guid? id, FormData optionalFormData = null)
{
    if (optionalFormData != null)
    {
        return View(optionalFormData);
    }

    return View(_context.Data.FirstOrDefault(x => x.Id == id.Value));
}


public class FormData
{
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string SecondName { get; set; }

    public File File { get; set; }
}

@Html.ActionLink("Enter MyView", "MyView", "MyController", new { id = Model?.Id })

我尝试过执行 FormData吗?optionalFormData ,但它需要C#8.0

I tried doing FormData? optionalFormData but it requires C# 8.0

我怎么在7.x上做到这一点?

How can I do that at 7.x?

推荐答案

对于Asp.Net核心模型绑定,它将在绑定过程中创建模型实例,并逐一设置属性.如果未提供该模型,则无法将其设置为null.

For Asp.Net Core Model Binding, it will create the model instance during binding process, and set the properties one by one. You could not set the model with null if it is not provided.

要解决此问题,您可以逐一检查模型属性,以查看它们是否为非空值的默认值和为空值的值是否为null.

For a workaround, you may check the model properties one by one to see whether they are default value for non-nullable and null for nullable value.

尝试

public static class Extensions
{
    public static bool IsNullOrDefault(this object obj)
    {
        if (Object.ReferenceEquals(obj, null))
            return true;

        return obj.GetType().GetProperties()
            .All(x => IsNullOrEmpty(x.GetValue(obj)));
    }

    private static bool IsNullOrEmpty(object value)
    {
        if (Object.ReferenceEquals(value, null))
            return true;

        var type = value.GetType();
        return type.IsValueType
            && Object.Equals(value, Activator.CreateInstance(type));
    }
}

并使用类似:

public IActionResult MyView(Guid? id, FormData optionalFormData = null)
{
    if (!optionalFormData.IsNullOrDefault())
    {
        return View(optionalFormData);
    }

    return View(_context.Data.FirstOrDefault(x => x.Id == id.Value));
}

这篇关于控制器的方法(http get):可选参数不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆