Asp.net
WebApi:將參數映射到標頭值
我已經做了一些搜尋,但似乎沒有找到任何東西……
使用 WebApi,我想將輸入參數映射到標頭值:例如
例如在控制器中:
public User GetUser(int id){ ... return user; }我希望 WebApi 將 id 參數映射到標頭值(例如 X-Auth: 1234)…而不是 URL 參數。
這支持嗎?
我不認為這是開箱即用的支持,例如 [FromBody] 屬性。如此處所述,您似乎應該能夠通過使用模型綁定器來實現此功能。在模型綁定器中,您可以訪問請求及其標頭,因此您應該能夠讀取標頭並將其值設置為 bindingContext.Model 屬性。
編輯:進一步閱讀文章,似乎自定義 HttpParameterBinding 和 ParameterBindingAttribute 是更合適的解決方案,或者至少我會這樣。您可以實現一個通用的 [FromHeader] 屬性來完成這項工作。我也在與同樣的問題作鬥爭,所以一旦我找到解決方案,我會發布我的解決方案。
編輯2:這是我的實現:
public class FromHeaderBinding : HttpParameterBinding { private string name; public FromHeaderBinding(HttpParameterDescriptor parameter, string headerName) : base(parameter) { if (string.IsNullOrEmpty(headerName)) { throw new ArgumentNullException("headerName"); } this.name = headerName; } public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { IEnumerable<string> values; if (actionContext.Request.Headers.TryGetValues(this.name, out values)) { actionContext.ActionArguments[this.Descriptor.ParameterName] = values.FirstOrDefault(); } var taskSource = new TaskCompletionSource<object>(); taskSource.SetResult(null); return taskSource.Task; } } public abstract class FromHeaderAttribute : ParameterBindingAttribute { private string name; public FromHeaderAttribute(string headerName) { this.name = headerName; } public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter) { return new FromHeaderBinding(parameter, this.name); } } public class MyHeaderAttribute : FromHeaderAttribute { public MyHeaderAttribute() : base("MyHeaderName") { } }然後你可以像這樣使用它:
[HttpGet] public IHttpActionResult GetItem([MyHeader] string headerValue) { ... }希望有幫助。