我正在使用示例 ASP.NET MVC 3 应用程序。我正在为我正在处理的项目的 API 进行概念验证,方法是使用HttpWebRequest
s. 我以 JSON 格式提交数据,并使用内容类型“application/json”。
这是我的方法:
[HttpPost]
[Api]
public bool ApiLogOn(LogOnModel model)
{
if (ModelState.IsValid && model != null)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return true;
}
}
return false;
}
问题是,即使ModelState
包含我希望看到的所有键和值(例如 Dictionary 包含 { "UserName"="username", "Password"="password", "RememberMe"=true } 这是三个属性LogOnModel 类),model
每次我调用该方法时,该对象都是空的。
使用“application/x-www-form-urlencoded”时我没有这个问题。我也尝试过添加和不添加
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
到我的Application_Start
方法。
这是我用来向上述方法发送请求的代码:
var credentials = new LogOnModel() { UserName = "username", Password = "password", RememberMe = true };
var result = PostData<LogOnModel, bool>(@"url goes here", credentials);
protected R PostData<T, R>(string uri, T postData)
{
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Headers.Add("X-Requested-With", X_REQUESTED_WITH_HEADER);
request.Accept = "application/json";
request.Method = "POST";
request.CookieContainer = cookieJar;
request.ContentType = "application/json";
var serializerT = new DataContractJsonSerializer(typeof(T));
var serializerR = new DataContractJsonSerializer(typeof(R));
if (postData != null)
{
using (var stream = request.GetRequestStream())
{
serializerT.WriteObject(stream, postData);
}
}
try
{
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (var stream = response.GetResponseStream())
{
var result = (R)serializerR.ReadObject(stream);
return result;
}
}
else
{
return default(R);
}
} catch { return default(R); }
}