gpt4 book ai didi

c# - 我无法访问我的 ApiController

转载 作者:太空狗 更新时间:2023-10-29 17:30:53 25 4
gpt4 key购买 nike

我正在尝试创建一个用于登录的 Api Controller ,应该在使用我的 CustomerController (Api) 访问数据之前使用它。

问题是当我尝试访问 AccountController 上的登录方法时出现 404 错误。我正在尝试 POST 到 AccountController,如下面的屏幕截图所示。

有趣的是,通过将浏览器指向 http://localhost:62655/api/customer/cvr/88888888,我可以毫无问题地访问我的 CustomerController (Api) 我是否缺少 POST 请求的约定或其他内容?

我的 WebApi 路由配置是:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

并添加到我的 Global.asax 中:

WebApiConfig.Register(GlobalConfiguration.Configuration);

我的 AccountController 和 CustomerController 看起来像这样(为简洁起见合并了文件):

public class AccountController : ApiController
{
public UserManager<ApplicationUser> UserManager { get; private set; }
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}

public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}

public async Task<HttpResponseMessage> Login([FromBody]LoginApiViewModel model)
{
if (!ModelState.IsValid) return Request.CreateResponse(HttpStatusCode.BadRequest, "Username or password is not supplied");

var user = UserManager.Find(model.Username, model.Password);
if (user != null && UserManager.IsInRole(user.Id, "Administrator"))
{
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);

var response = Request.CreateResponse(HttpStatusCode.OK, "Success");
return response;
}

return Request.CreateResponse(HttpStatusCode.Unauthorized, "Wrong login");
}
}

[Authorize(Roles = "Administrator")]
public class CustomerController : ApiController
{
private readonly ICustomerService _customerService;

public CustomerController(ICustomerService customerService)
{
_customerService = customerService;
}

[ActionName("cvr")]
public CustomerApiViewModel GetCustomerById(string id)
{
var customer = _customerService.GetByCVR(id);
if (customer == null) throw new HttpResponseException(HttpStatusCode.NotFound);
var customerViewModel = Mapper.Map<CustomerApiViewModel>(customer);

return customerViewModel;
}
}

enter image description here

上图返回 404 错误。程序是Fiddler2。

异常(exception):

[HttpException]: The controller for path '/api/account/login' was not found or does not implement IController.

根据评论,更新-(完成Global.asax和RouteConfig (MVC)

 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperWebConfiguration.Configure();

GlobalConfiguration.Configuration.EnsureInitialized();
}

public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"DefaultOnlyAction",
"{action}",
new { controller = "Home", action = "Index" }
);

routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

最佳答案

将您的配置更改为如下所示...这里我将 Web API 路由移到 MVC 路由之前...这是因为 Web API 路由比通用 MVC 路由更具体..

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

GlobalConfiguration.Configure(WebApiConfig.Register);

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

AutoMapperWebConfiguration.Configure();
}

关于c# - 我无法访问我的 ApiController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20957074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com