Guest User

Untitled

a guest
Aug 20th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.99 KB | None | 0 0
  1. [FromHeader] Guid id
  2.  
  3. public IModelBinder GetBinder(ModelBinderProviderContext context)
  4. {
  5. if (context == null)
  6. {
  7. throw new ArgumentNullException(nameof(context));
  8. }
  9.  
  10. if (context.BindingInfo.BindingSource != null &&
  11. context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Header))
  12. {
  13. // We only support strings and collections of strings. Some cases can fail
  14. // at runtime due to collections we can't modify.
  15. if (context.Metadata.ModelType == typeof(string) ||
  16. context.Metadata.ElementType == typeof(string))
  17. {
  18. return new HeaderModelBinder();
  19. }
  20. }
  21.  
  22. return null;
  23. }
  24.  
  25. public class GuidHeaderModelBinder : IModelBinder
  26. {
  27. public Task BindModelAsync(ModelBindingContext bindingContext)
  28. {
  29. if (bindingContext.ModelType != typeof(Guid)) return Task.CompletedTask;
  30. if (!bindingContext.BindingSource.CanAcceptDataFrom(BindingSource.Header)) return Task.CompletedTask;
  31.  
  32. var headerName = bindingContext.ModelName;
  33. var stringValue = bindingContext.HttpContext.Request.Headers[headerName];
  34. bindingContext.ModelState.SetModelValue(bindingContext.ModelName, stringValue, stringValue);
  35.  
  36. // Attempt to parse the guid
  37. if (Guid.TryParse(stringValue, out var valueAsGuid))
  38. {
  39. bindingContext.Result = ModelBindingResult.Success(valueAsGuid);
  40. }
  41.  
  42. return Task.CompletedTask;
  43. }
  44. }
  45.  
  46. public IActionResult SampleAction(
  47. [FromHeader(Name = "my-guid")][ModelBinder(BinderType = typeof(GuidHeaderModelBinder))]Guid foo)
  48. {
  49. return Json(new { foo });
  50. }
  51.  
  52. $.ajax({
  53. method: 'GET',
  54. headers: { 'my-guid': '70e9dfda-4982-4b88-96f9-d7d284a10cb4' },
  55. url: '/home/sampleaction'
  56. });
  57.  
  58. public async Task BindModelAsync(ModelBindingContext BindingContext)
  59. {
  60. // Read HTTP header.
  61. string headerName = BindingContext.FieldName;
  62. if (BindingContext.HttpContext.Request.Headers.ContainsKey(headerName))
  63. {
  64. StringValues headerValues = BindingContext.HttpContext.Request.Headers[headerName];
  65. if (headerValues == StringValues.Empty)
  66. {
  67. // Value not found in HTTP header. Substitute empty GUID.
  68. BindingContext.ModelState.SetModelValue(BindingContext.FieldName, headerValues, Guid.Empty.ToString());
  69. BindingContext.Result = ModelBindingResult.Success(Guid.Empty);
  70. }
  71. else
  72. {
  73. // Value found in HTTP header.
  74. string correlationIdText = headerValues[0];
  75. BindingContext.ModelState.SetModelValue(BindingContext.FieldName, headerValues, correlationIdText);
  76. // Parse GUID.
  77. BindingContext.Result = Guid.TryParse(correlationIdText, out Guid correlationId)
  78. ? ModelBindingResult.Success(correlationId)
  79. : ModelBindingResult.Failed();
  80. }
  81. }
  82. else
  83. {
  84. // HTTP header not found.
  85. BindingContext.Result = ModelBindingResult.Failed();
  86. }
  87. await Task.FromResult(default(object));
  88. }
  89.  
  90. public class GuidHeaderModelBinderProvider : IModelBinderProvider
  91. {
  92. public IModelBinder GetBinder(ModelBinderProviderContext Context)
  93. {
  94. if (Context.Metadata.ModelType == typeof(Guid))
  95. {
  96. if (Context.BindingInfo.BindingSource == BindingSource.Header)
  97. {
  98. return new BinderTypeModelBinder(typeof(GuidHeaderModelBinder));
  99. }
  100. }
  101. return null;
  102. }
  103. }
  104.  
  105. [HttpGet("getbars")]
  106. public async Task<string> GetBarsAsync([FromHeader] Guid CorrelationId, int Count)
  107. {
  108. Logger.Log(CorrelationId, $"Creating {Count} foo bars.");
  109. StringBuilder stringBuilder = new StringBuilder();
  110. for (int count = 0; count < Count; count++)
  111. {
  112. stringBuilder.Append("Bar! ");
  113. }
  114. return await Task.FromResult(stringBuilder.ToString());
  115. }
  116.  
  117. // Add MVC and configure model binding.
  118. Services.AddMvc(Options =>
  119. {
  120. Options.ModelBinderProviders.Insert(0, new GuidHeaderModelBinderProvider());
  121. });
Add Comment
Please, Sign In to add comment