我已经设置了一个 web api 以允许使用基本身份验证进行跨域访问。当我向 API 发出跨域 GET 请求时,它工作正常,并且我在自定义消息处理程序的“授权”标头中获取令牌。但是在发起跨域 POST 请求时,我没有得到“授权”标头,这就是无法验证请求的原因。
任何帮助将不胜感激。
以下是用于跨域访问的自定义消息处理程序的代码。
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MyWebApi.Handlers
{
public class XHttpMethodOverrideDelegatingHandler : DelegatingHandler
{
static readonly string[] HttpOverrideMethods = { "PUT", "DELETE" };
static readonly string[] AccessControlAllowMethods = { "POST", "PUT", "DELETE" };
private const string HttpMethodOverrideHeader = "X-HTTP-Method-Override";
private const string OriginHeader = "ORIGIN";
private const string AccessControlAllowOriginHeader = "Access-Control-Allow-Origin";
private const string AccessControlAllowMethodsHeader = "Access-Control-Allow-Methods";
private const string AccessControlAllowHeadersHeader = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var authHeader = request.Headers.Authorization;
if (authHeader == null || authHeader.Scheme != "Basic" || string.IsNullOrWhiteSpace(authHeader.Parameter))
{
return CreateUnauthorizedResponse();
}
if (request.Method == HttpMethod.Post && request.Headers.Contains(HttpMethodOverrideHeader))
{
var httpMethod = request.Headers.GetValues(HttpMethodOverrideHeader).FirstOrDefault();
if (HttpOverrideMethods.Contains(httpMethod, StringComparer.InvariantCultureIgnoreCase))
request.Method = new HttpMethod(httpMethod);
}
var httpResponseMessage = base.SendAsync(request, cancellationToken);
if (request.Method == HttpMethod.Options && request.Headers.Contains(OriginHeader))
{
httpResponseMessage.Result.Headers.Add(AccessControlAllowOriginHeader, request.Headers.GetValues(OriginHeader).FirstOrDefault());
httpResponseMessage.Result.Headers.Add(AccessControlAllowMethodsHeader, String.Join(", ", AccessControlAllowMethods));
httpResponseMessage.Result.Headers.Add(AccessControlAllowHeadersHeader, HttpMethodOverrideHeader);
httpResponseMessage.Result.StatusCode = HttpStatusCode.OK;
}
//No mater what the HttpMethod (POST, PUT, DELETE), if a Origin Header exists, we need to take care of it
else if (request.Headers.Contains(OriginHeader))
{
httpResponseMessage.Result.Headers.Add(AccessControlAllowOriginHeader, request.Headers.GetValues(OriginHeader).FirstOrDefault());
}
return httpResponseMessage;
}
private Task<HttpResponseMessage> CreateUnauthorizedResponse()
{
var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.Headers.Add("WWW-Authenticate", "Basic");
var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
taskCompletionSource.SetResult(response);
return taskCompletionSource.Task;
}
}
}
我已经在 Application_Start 中注册了上述处理程序,如下所示:
namespace MyWebApi
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional});
GlobalConfiguration.Configuration.MessageHandlers.Add(new XHttpMethodOverrideDelegatingHandler());
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
}
}
}
在不同域项目的客户端,我正在尝试使用以下代码添加新记录。
AddUser {
var jsonData = {
"FirstName":"My First Name",
"LastName": "My Last Name",
"Email": "my.name@mydomain.com",
"Password": "MyPa$$word"
};
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost:4655/api/user/signup",
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxx"); },
accept: "application/json",
data: JSON.stringify(jsonData),
success: function (data) {
alert("success");
},
failure: function (errorMsg) {
alert(errorMsg);
},
error: function (onErrorMsg) {
alert(onErrorMsg.statusText);
},
statusCode: function (test) {
alert("status");
}
});
});
以下是我的用户控制器的代码。
namespace MyWebApi.Controllers
{
public class UserController : ApiController
{
[HttpPost]
[ActionName("Adduser")]
public int Post(UserModel source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
Db.Users.Add(source);
Db.SaveChanges();
return source.UserId;
}
}
}
提前致谢!