我正在开展一个ASP.Net MVC 5
项目,该项目最近需要使用Web API
通过POST
将一些数据发送到另一台服务器。
它更像是中间API
,它通过POST
获取一些数据并将其发送到另一台服务器。
此API
需要使用username
和password
进行身份验证。
此项目中的默认身份验证为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
。为什么呢?