我正在关注本教程:http://www.mithunvp.com/create-aspnet-mvc-6-web-api-visual-studio-2015/
哪个应该是最新的,应该适用于rc2
的信息: 操作系统:赢10 x64 14257 VS:15 Update 1 DNX:1.0.0-rc2-16357 clr x86
错误:
CS0592 Attribute 'FromServices' is not valid on this declaration type. It is only valid on 'parameter' declarations.
WebAPIController
[Route("api")]
public class WebAPIController : Controller
{
[FromServices]
IWebAPIRepository WebAPI { get; set; }
[HttpPost("Authenticate", Name = "Authenticate")] // /api/Authenticate
public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
{
if (model == null)
return Ok(new { success = false });
AuthenticationStatus result = await WebAPI.Authenticate(HttpContext.Authentication, model.Email, model.Password, model.RememberMe);
switch (result)
{
case AuthenticationStatus.Success:
return Ok(new { success = true });
case AuthenticationStatus.LockedOut:
return Ok(new { success = false, error = "Locked out" });
case AuthenticationStatus.Failure:
default:
return Ok(new { success = false, error = "Invalid login attempt" });
}
}
}
该教程应该没问题
WebAPIRepository(包含在同一文件中的接口,位置模型文件夹)
public interface IWebAPIRepository
{
Task<AuthenticationStatus> Authenticate(AuthenticationManager manager, string email, string password, bool rememberMe);
}
public enum AuthenticationStatus
{
Success,
LockedOut,
Failure
}
public class WebAPIRepository : IWebAPIRepository
{
public async Task<AuthenticationStatus> Authenticate(AuthenticationManager manager, string email, string password, bool rememberMe)
{
// ......
await manager.SignInAsync("Cookies", new ClaimsPrincipal(id));
return AuthenticationStatus.Success;
}
}
最后是Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IWebAPIRepository, WebAPIRepository>();
}
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseDeveloperExceptionPage();
app.UseCookieAuthentication(options =>
{
options.LoginPath = "/account/login";
options.AccessDeniedPath = "/account/forbidden";
options.AuthenticationScheme = "Cookies";
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseStaticFiles();
}
public static void Main(string[] args)
{
var application = new WebApplicationBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args))
.UseStartup<Startup>()
.Build();
application.Run();
}
可能出现什么问题?
答案 0 :(得分:5)
所以我想出了解决方案:
IWebAPIRepository WebAPI { get; set; }
public WebAPIController([FromServices] IWebAPIRepository API)
{
WebAPI = API;
}
希望这有助于其他人:))