使用带身份验证的HttpClient将数据发布到Web Api 2

时间:2016-06-23 10:51:29

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-identity

我正在开展一个ASP.Net MVC 5项目,该项目最近需要使用Web API通过POST将一些数据发送到另一台服务器。

它更像是中间API,它通过POST获取一些数据并将其发送到另一台服务器。 此API需要使用usernamepassword进行身份验证。

此项目中的默认身份验证为ASP.Net Identity 2

现在我的问题是我通过HttpClient传递的身份验证无效并返回status code 200和登录路径。

这是我的API控制器:

public class SendController : ApiController
{
    [Authorize]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [Route("~/api/send/data")]
    public IHttpActionResult PostData(Product data)
    {
        return Ok("done.");
    }
} 

我正在使用的代码:

using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:2494/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(
                    "Basic",
                    Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                            string.Format("{0}:{1}", "kamal", "123456"))));

            // HTTP GET
            HttpResponseMessage response = await client.GetAsync("api/send");

            // HTTP POST
            var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
            response = await client.PostAsJsonAsync("api/send/data", gizmo);
            if (response.IsSuccessStatusCode)
            {
                // 
            }
        }

这是回复信息:

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  X-Frame-Options: SAMEORIGIN
  X-SourceFiles: =?UTF-8?B?RDpcd29ya1xfXFNtc0FwaVxTbXNBcGkuV2ViXGFjY291bnRcbG9naW4=?=
  Cache-Control: private
  Date: Fri, 24 Jun 2016 03:04:32 GMT
  Set-Cookie: __RequestVerificationToken=D0tzqAqeERwp2EPr9V0_MYGn0syYsoBeBTS6C28sjPVo436KO837RC_iXZQstD3bqrH5EGKry7gHCFoqvg8ZNpDVDgA1; path=/; HttpOnly
  X-Powered-By: ASP.NET
  Content-Length: 2700
  Content-Type: text/html; charset=utf-8
}}

请求消息:

{Method: POST, RequestUri: 'http://localhost:2494/Account/Login?ReturnUrl=%2Fapi%2Fsend%2Fdata', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[SmsApi.Web.Models.Product, SmsApi.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Headers:
{
  Accept: application/json
  Authorization: Basic a2FtYWw6MTIzNDU2Nzg5MDA=
  Content-Type: application/json; charset=utf-8
  Content-Length: 50
}}

我需要在项目中设置一些配置吗?

还有一些让我困惑的事情,如果我删除Authorize属性,帖子请求将起作用,但它也需要发送一个获取请求。我的意思是如果我评论获取请求,帖子请求将返回Methos Not Allow。为什么呢?

0 个答案:

没有答案