2017-02-24 196 views
4

結合一個GUID參數我想一個GUID參數綁定到我的ASP.NET MVC核心API:在asp.net mvc的核心

[FromHeader] Guid id 

但它總是空。如果我將參數更改爲字符串並手動解析字符串中的Guid,它會起作用,所以我認爲它沒有將Guid檢測爲可轉換類型。

the documentation它說

在MVC簡單類型與字符串類型轉換器任何.NET基本類型或類型。

Guid有一個類型轉換器(GuidConverter),但也許ASP.NET MVC核心不知道它。

有誰知道如何綁定一個Guid參數與ASP.NET MVC核心或如何告訴它使用GuidConverter?

+0

怎麼樣使用FromBody屬性? –

+0

我使用的FromHeader屬性,因爲我想要的值是在標題不是正文 – ghosttie

+0

只是爲了澄清,這似乎是''[FromHeader]'綁定源特定的問題。我可以從查詢字符串和正文中正確綁定Guid。 –

回答

7

我剛剛發現,基本上ASP核心只支持字符串和字符串集合的綁定標題值! (而來自路徑的值,查詢字符串和身體的結合支持任何複雜類型)

您可以檢查HeaderModelBinderProvidersource 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' 
});