加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在asp.net mvc核心中绑定一个Guid参数

发布时间:2020-12-15 04:31:34 所属栏目:百科 来源:网络整理
导读:我想将Guid参数绑定到我的ASP.NET MVC Core API: [FromHeader] Guid id 但它总是空的.如果我将参数更改为字符串并手动解析字符串中的Guid,那么我认为它不会将Guid视为可转换类型. 在the documentation它说 In MVC simple types are any .NET primitive type
我想将Guid参数绑定到我的ASP.NET MVC Core API:
[FromHeader] Guid id

但它总是空的.如果我将参数更改为字符串并手动解析字符串中的Guid,那么我认为它不会将Guid视为可转换类型.

在the documentation它说

In MVC simple types are any .NET primitive type or type with a string type converter.

Guids(GuidConverter)有一个类型转换器,但是ASP.NET MVC Core可能不知道它.

有谁知道如何将Guid参数与ASP.NET MVC Core绑定或如何告诉它使用GuidConverter?

解决方法

我刚刚发现,基本上ASP Core只支持将字符串绑定到字符串和字符串集合! (从路由值绑定,查询字符串和正文支持任何复杂类型)

您可以查看HeaderModelBinderProvider source in Github并亲自查看:

public IModelBinder GetBinder(ModelBinderProviderContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException(nameof(context));
    }

    if (context.BindingInfo.BindingSource != null &&
            context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Header))
    {
        // We only support strings and collections of strings. Some cases can fail
        // at runtime due to collections we can't modify.
        if (context.Metadata.ModelType == typeof(string) ||
            context.Metadata.ElementType == typeof(string))
        {
            return new HeaderModelBinder();
        }
    }

    return null;
}

我已经提交了new issue,但在此期间我建议您绑定一个字符串或创建自己的特定模型绑定器(将[FromHeader]和[ModelBinder]组合到您自己的绑定器中的东西)

编辑

样本模型绑定器可能如下所示:

public class GuidHeaderModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(Guid)) return Task.CompletedTask;
        if (!bindingContext.BindingSource.CanAcceptDataFrom(BindingSource.Header)) return Task.CompletedTask;

        var headerName = bindingContext.ModelName;
        var stringValue = bindingContext.HttpContext.Request.Headers[headerName];
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName,stringValue,stringValue);

        // Attempt to parse the guid                
        if (Guid.TryParse(stringValue,out var valueAsGuid))
        {
            bindingContext.Result = ModelBindingResult.Success(valueAsGuid);
        }

        return Task.CompletedTask;
    }
}

这将是一个使用它的例子:

public IActionResult SampleAction(
    [FromHeader(Name = "my-guid")][ModelBinder(BinderType = typeof(GuidHeaderModelBinder))]Guid foo)
{
    return Json(new { foo });
}

您可以尝试使用,例如在浏览器中使用jquery:

$.ajax({
  method: 'GET',headers: { 'my-guid': '70e9dfda-4982-4b88-96f9-d7d284a10cb4' },url: '/home/sampleaction'
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读