【问题标题】:Not able to access web api calls in a api/controller format无法访问 api/controller 格式的 web api 调用
【发布时间】: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


【解决方案1】:

我会用这样的属性路由来装饰 post 方法

[RoutePrefix("api/NCT_Login")]
public class NCT_LoginController : ApiController
{
    public NCTEntities entityObject = new NCTEntities();
    [EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE")]

    [Route("Login")]
    [HttpPost]
    public IHttpActionResult Post(LoginClass obj)
    {

这会将路由设置为api/NCT_Login/Login

IMO 使用attribute routing 是一个很好的做法,因为它非常清楚每种方法路线是什么。 此外,当控制器增长时,很容易在同一个 http 动词上定义新路由

【讨论】:

  • 确保他在 api 配置中启用了属性路由,并且您可以保留 [Route()] 用于登录操作,以便可以将其发布到 api/NCT_Login/ 本身:)
  • @Developer 不是在 web api 2 中默认启用属性路由吗?
  • @NiranjanGodbole 是的,那将是正确的路线:)
  • 工作正常。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多