webservice post的授权标头为null

时间:2016-02-10 00:52:52

标签: c# authentication dotnet-httpclient

我正在编写一个C# WinForms应用程序,我将一个对象发布到Web API 2 Web服务。我正在为身份验证请求添加AuthenticationHeaderValue

webservice将AuthenticationHeaderValue显示为null。

以下代码是null的代码。

AuthenticationHeaderValue authorization = request.Headers.Authorization

这是webservice post功能:

[System.Web.Http.HttpPost]
[Route("Posttemplate")]
[ResponseType(typeof(Template))]
public async Task<IHttpActionResult> PostTemplate(Template template)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    dbSetService.AddObj(template);
    await dbSetService.SaveChangesAsync();

    return Ok(template);
}

这是HttpClient代码:

private async void TestPost()
{
    var template = new Template();
    template.id = 2;
    template.name = "Test";

    string requestUri = "http://localhost/Posttemplate";
    using (HttpClient client = new HttpClient())
    {
        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri))
        {
            request.Headers.Authorization = CreateBasicCredentials("user", "password");
            using (HttpResponseMessage response = await client.PostAsJsonAsync(requestUri, template))
            {
                if (response.IsSuccessStatusCode)
                {
                    var responseItem = await response.Content.ReadAsAsync<Template>();
                }
                else
                {
                    throw new HttpRequestException(message: response.ReasonPhrase);
                }
            }
        }
    }
}
static AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
{
    string toEncode = userName + ":" + password;
    // The current HTTP specification says characters here are ISO-8859-1.
    // However, the draft specification for the next version of HTTP indicates this encoding is infrequently
    // used in practice and defines behavior only for ASCII.
    Encoding encoding = Encoding.GetEncoding("iso-8859-1");
    byte[] toBase64 = encoding.GetBytes(toEncode);
    string parameter = Convert.ToBase64String(toBase64);

    return new AuthenticationHeaderValue("Basic", parameter);
}

有人可以帮我解释一下这段代码吗?

0 个答案:

没有答案