在POST数据中从Api控制器重定向到MVC控制器

时间:2016-06-08 13:45:12

标签: c# asp.net-mvc asp.net-web-api

我是MVC和Web API的新手。我被击中了。我们有一个APIController和MVC控制器。这里的API控制器有CreateEmployee(Employee Data),在Action方法里面,它应该调用MVC控制器Register(Employee Emp)Action方法。

  • 如何从APIController重定向到MVC控制器..?

  • 怎么可能......?

当我尝试在WebApi的CreateEMployee中创建MVC控制器的Object时,数据显示在MVC Controller中,但不会插入到ASPNetUsers表中。如何在不创建对象的情况下完成。建议将不胜感激..

APIController

[HttpPost]

Public Void CreateEmployee(Employee Emp)

{

  //how to redirect here to MVC Controller without creating object of the  mvc contoller..

}

// MVC控制器

 public class EmployeeRegController : Controller

{
    ApplicationDbContext db = new ApplicationDbContext();
    private ApplicationUserManager _userManager;
public EmployeeRegController()
{
}
public EmployeeRegController(ApplicationUserManager userManager)
{
    UserManager = userManager;
}
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}

public ActionResult Register(Employee Emp)
{
    try
    {
        RegisterViewModel RVM = new RegisterViewModel();
        RVM.Email = Emp.EmpFirstName + "." + Emp.EmpLastName +"@gmail.com";
        RVM.Password = "Password@123";
        RVM.ConfirmPassword = "Password@123";
        db.Employees.Add(Emp);
        db.SaveChanges();
        CreateEmp(RVM);
     }
    catch(Exception ex1)
    {
        throw ex1;
    }
}

    public void CreateEmp(RegisterViewModel regModel)
    {
        if (ModelState.IsValid)
        {
            try
            {
                var user = new ApplicationUser() { UserName =regModel.Email, Email = regModel.Email };
                var result = UserManager.Create(user, regModel.Password);
            }
            catch (Exception ex1)
            {
                throw ex1;
            }
        }
    }

    // GET: EmployeeReg

    public ActionResult Index()
    {
        return View();
    }
}

2 个答案:

答案 0 :(得分:1)

Web Api操作不应重定向到MVC操作。 Web Api的重点是促进与瘦客户端的交互,瘦客户端可能完全无法呈现甚至解析HTML文档。

您可能希望这样做,因为您不想在MVC操作中重复注册代码。但是,正确的方法是将代码分解为一个类Web库,您的Web Api操作和MVC操作都可以使用它们。

答案 1 :(得分:1)

我同意Chris你不应该这样做,并且有更好的方法来重用代码。

那就是说,我有一个过去曾用过的功能来帮助建立链接,因为其他原因(比如发送电子邮件)会对你有用。

return Redirect(MvcURL("Index", "Home", null));

基本上,它构建了MVC的url帮助器,因此您可以将结果字符串重定向到。

private static string MvcURL(string routeName, string controller, object routeValues)
{
    var urlHelper = new System.Web.Mvc.UrlHelper(
        new RequestContext(
            new HttpContextWrapper(HttpContext.Current),
            HttpContext.Current.Request.RequestContext.RouteData), 
        RouteTable.Routes);

    return urlHelper.Action(routeName, controller, routeValues, HttpContext.Current.Request.Url.Scheme);
}

我没有对性能进行测试,所以请不要只是从WebAPI重定向到MVC。

相关问题