本文介绍了如何使用IHttpActionResult设置标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将令牌添加到webapi请求的标头中.我怎样才能做到这一点 ?

i want to add token to header for webapi request.how can i do this ?

这是我的示例代码

public IHttpActionResult Authenticate(Login data)
            {
                var Token = "fdsf123546fskjhf-gsuyuhsh";

                //here add these token to header

                return ?
            }

谢谢.

推荐答案

  1. 您可以使用 ResponseMessageResult 类:

public IHttpActionResult Authenticate(Login data)
{
    var Token = "fdsf123546fskjhf-gsuyuhsh";

    var response = new HttpResponseMessage();

    response.Headers.Add("Authentication", Token);

    return new ResponseMessageResult(response);
}

  • 或创建自己的结果类:

  • Or create your own result class:

    public class HeaderActionResult : IHttpActionResult
    {
        private Tuple<string, string> header;
    
        public HeaderActionResult(Tuple<string, string> header) 
        {
            this.header = header;
        }
    
        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
        {
            var response = new HttpResponseMessage();
    
            response.Headers.Add(header.Item1, header.Item2);
    
            return Task.FromResult<HttpResponseMessage>(response);
        }
    }
    
    public IHttpActionResult Authenticate(Login data)
    {
        var Token = "fdsf123546fskjhf-gsuyuhsh";
    
        return new HeaderActionResult(Tuple.Create("Authentication", Token));
    }
    

  • 或使用扩展方法将标头添加到任何现有的IHttpActionResult对象:

  • Or add a header to any existing IHttpActionResult object using an extension method:

    public static class HttpActionResultExtensions
    {
        public static IHttpActionResult AddHeader(this IHttpActionResult actionResult, string name, string value)
        {
            return new HeaderActionResult(actionResult, name, value);
        }
    
        private class HeaderActionResult : IHttpActionResult
        {
            private readonly IHttpActionResult actionResult;
    
            private string name;
    
            private string value;
    
            public HeaderActionResult(IHttpActionResult actionResult, string name, string value)
            {
                this.actionResult = actionResult;
    
                this.name = name;
    
                this.value = value;
            }
    
            public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                HttpResponseMessage httpResponseMessage = await this.actionResult.ExecuteAsync(cancellationToken);
    
                httpResponseMessage.Headers.Add(this.name, this.value);
    
                return httpResponseMessage;
            }
        }
    }
    

  • 这篇关于如何使用IHttpActionResult设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-26 16:07