【发布时间】:2017-06-16 11:51:41
【问题描述】:
您好,我正在使用 web api2 开发一个应用程序并通过 angularjs 访问调用。我创建了 web api 调用并托管在 iis 服务器(公共 ip)中。我正在访问以下格式的 web api2 方法。
$http.post('http://111.93.133.98:4500/api/NCT_Login/', credentials).success(function (response) { alert(response); });
这是我的 web api config.cs 文件。
routeTemplate: "api/{controller}/{id}"
这是我的控制器代码。
public class NCT_LoginController : ApiController
{
public NCTEntities entityObject = new NCTEntities();
[EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE")]
public IHttpActionResult Post(LoginClass obj)
{
try
{
if (ModelState.IsValid)
{
obj.User_Password = PasswordEncryption.sha256_hash(obj.User_Password);
bool result = (from c in entityObject.NCT_UserRegistration where obj.User_Name ==c.User_Name && obj.User_Password == c.User_Password select c).Any();
if(result==true)
{
obj.UserRole = (from c in entityObject.NCT_UserRegistration where obj.User_Name == c.User_Name && obj.User_Password == c.User_Password select c.User_Role).FirstOrDefault();
obj.Success = 0;
obj.User_Password = "";
var response = Request.CreateResponse(HttpStatusCode.OK, obj);
var newSessionId = new SessionIDManager().CreateSessionID(HttpContext.Current);
var cookie = new CookieHeaderValue("session-id", newSessionId);
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
response.Headers.AddCookies(new[] { cookie });
return ResponseMessage(response);
}
else
{
return Content(HttpStatusCode.BadRequest, 1);
}
}
else
{
return Content(HttpStatusCode.BadRequest, 1);
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
如果我从路由模板中删除 api,我可以访问 api,如果我输入 api.NCT_Login,那么我会收到预检错误。我不确定我在这里缺少什么。任何帮助,将不胜感激。谢谢。
【问题讨论】:
-
请分享完整的控制器类
-
我们还需要控制器类名:)
-
对不起。 API 名称是 NCT_LoginController。 Mvc5 控制器名称是 Homecontroller。
标签: angularjs asp.net-mvc-5 asp.net-web-api2