1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個(gè)贊
這就是它不具有約束力的原因嗎?
原因是您的操作方法需要accessToken來(lái)自請(qǐng)求標(biāo)頭:
public async Task<ActionResult> GetAccountAsync([FromHeader] string accessToken)
AccessToken: xxx_yyy_zzz雖然您在 request 中沒有這樣的標(biāo)頭。
如果您發(fā)送如下請(qǐng)求:
GET https://localhost:44323/api/values/account HTTP/1.1
accessToken : xxx_yyy_zzz
ModelBinder 將綁定accessToken.
如果是這樣,我該如何正確傳遞它?
我不確定您為什么要accessToken在操作方法內(nèi)獲取。但是,如果您確實(shí)需要模型綁定的訪問令牌,那么至少有兩種方法可以做到這一點(diǎn):
一種方法是更改您的操作方法以Authorization直接獲取標(biāo)題:
public async Task<ActionResult> GetAccount2Async([FromHeader] string authorization)
{
if (String.IsNullOrEmpty(authorization)) { /* */ }
if (!authorization.StartsWith("accessToken",StringComparison.OrdinalIgnoreCase)) { /* */ }
var token = authorization.Substring("accessToken".Length).Trim();
// ...
}
當(dāng)您發(fā)送標(biāo)頭為Authorization : accessToken xxx_yyy_zzz.
但是,上面的方法并不干凈。更好的方法是創(chuàng)建自定義ModelBinder.
首先讓我們創(chuàng)建一個(gè)虛擬類來(lái)保存 accessToken 值:
public class AccessTokenAuthorizationHeader
{
public string TokenValue { get; set; }
}
這是一個(gè)簡(jiǎn)單的模型綁定器,它將從 headers 中檢索訪問令牌:
public class AuthorizationHeaderBinder : IModelBinder
{
const string DEFAULT_ACCESS_TOKEN_AUTH_HEADER_PREFIX = "accessToken";
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); }
var modelName = bindingContext.BinderModelName;
if (string.IsNullOrEmpty(modelName)) { modelName = DEFAULT_ACCESS_TOKEN_AUTH_HEADER_PREFIX; }
var authorization = bindingContext.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
if (String.IsNullOrWhiteSpace(authorization)) {
return Task.CompletedTask;
}
if (!authorization.StartsWith(modelName, StringComparison.OrdinalIgnoreCase)) {
return Task.CompletedTask;
}
var token = authorization.Substring(modelName.Length).Trim();
bindingContext.Result = ModelBindingResult.Success(new AccessTokenAuthorizationHeader() {
TokenValue =token,
});
return Task.CompletedTask;
}
}
最后,AccessTokenAuthorizationHeader用一個(gè)ModelBinderAttribute:
[ModelBinder(BinderType =typeof(AuthorizationHeaderBinder))]
public class AccessTokenAuthorizationHeader
{
public string TokenValue { get; set; }
}
現(xiàn)在我們可以自動(dòng)綁定它了:
[HttpGet("Account3")]
public async Task<ActionResult> GetAccount3Async(AccessTokenAuthorizationHeader accessToken) {
var result =new JsonResult(accessToken?.TokenValue);
return result;
}
讓我們用一個(gè) requset 測(cè)試它:
GET https://localhost:44323/api/values/account3 HTTP/1.1
Authorization : accessToken 111111
響應(yīng)將是:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-SourceFiles: =?UTF-8?B?RDpccmVwb3J0XDIwMThcOVw5LTEzXFNPLkF1dGhvcml6YXRpb25IZWFkZXJcQXBwXEFwcFxhcGlcdmFsdWVzXGFjY291bnQz?=
X-Powered-By: ASP.NET
Date: Thu, 13 Sep 2018 01:54:25 GMT
"111111"
- 1 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報(bào)