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

前端之家收集整理的这篇文章主要介绍了c# – 在asp.net mvc核心中绑定一个Guid参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将Guid参数绑定到我的ASP.NET MVC Core API:
  1. [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并亲自查看:

  1. public IModelBinder GetBinder(ModelBinderProviderContext context)
  2. {
  3. if (context == null)
  4. {
  5. throw new ArgumentNullException(nameof(context));
  6. }
  7.  
  8. if (context.BindingInfo.BindingSource != null &&
  9. context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Header))
  10. {
  11. // We only support strings and collections of strings. Some cases can fail
  12. // at runtime due to collections we can't modify.
  13. if (context.Metadata.ModelType == typeof(string) ||
  14. context.Metadata.ElementType == typeof(string))
  15. {
  16. return new HeaderModelBinder();
  17. }
  18. }
  19.  
  20. return null;
  21. }

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

编辑

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

  1. public class GuidHeaderModelBinder : IModelBinder
  2. {
  3. public Task BindModelAsync(ModelBindingContext bindingContext)
  4. {
  5. if (bindingContext.ModelType != typeof(Guid)) return Task.CompletedTask;
  6. if (!bindingContext.BindingSource.CanAcceptDataFrom(BindingSource.Header)) return Task.CompletedTask;
  7.  
  8. var headerName = bindingContext.ModelName;
  9. var stringValue = bindingContext.HttpContext.Request.Headers[headerName];
  10. bindingContext.ModelState.SetModelValue(bindingContext.ModelName,stringValue,stringValue);
  11.  
  12. // Attempt to parse the guid
  13. if (Guid.TryParse(stringValue,out var valueAsGuid))
  14. {
  15. bindingContext.Result = ModelBindingResult.Success(valueAsGuid);
  16. }
  17.  
  18. return Task.CompletedTask;
  19. }
  20. }

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

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

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

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

猜你在找的C#相关文章