简体   繁体   English

如何从 controller 获取 id 并将其传递给 c# 中的另一个 controller

[英]How to get an id from a controller and pass it to another controller in c#

I am using entity framework on a WebAPI based on .NET Core and i need to get an id from a controller and pass it to another controller where i need to store in in the database.我在基于 .NET 核心的 WebAPI 上使用实体框架,我需要从 controller 获取 id 并将其传递给另一个 controller 我需要存储在数据库中。 First of all, in the Controller1 i have a method Create() where i return a user and there is the moment when the id is assigned.首先,在 Controller1 中,我有一个 Create() 方法,我在其中返回一个用户,并且有一个分配 id 的时刻。

public User Create(User user, string password)
    {
        // validation
        if (string.IsNullOrWhiteSpace(password))
            throw new AppException("Password is required");

        if (_context.Users.Any(x => x.Username == user.Username))
            throw new AppException("Username \"" + user.Username + "\" is already taken");

        byte[] passwordHash, passwordSalt;
        CreatePasswordHash(password, out passwordHash, out passwordSalt);

        user.PasswordHash = passwordHash;
        user.PasswordSalt = passwordSalt;


        _context.Users.Add(user);
        _context.SaveChanges();
     
        return user;
    }

In the last step, the 'user' which is returned already have the property id set.在最后一步中,返回的“用户”已经设置了属性 ID。 After that i need to get the user.Id and pass it to the Controller2 which is like this:之后,我需要获取 user.Id 并将其传递给 Controller2,如下所示:

 [HttpPost]
    public async Task<ActionResult<PaymentDetail>> PostPaymentDetail(PaymentDetail paymentDetail)
    {    
        _context.PaymentDetails.Add(paymentDetail);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetPaymentDetail", new { id = paymentDetail.PMId}, paymentDetail);
    }

I think i need something like user.Id = paymentDetail.userId.我想我需要像 user.Id = paymentDetail.userId 这样的东西。

Here is the Controller1 from where i call the Create() method:这是我调用 Create() 方法的 Controller1:

 [HttpPost("register")]
    public IActionResult Register([FromBody]RegisterModel model)
    {
        // map model to entity
        var user = _mapper.Map<User>(model);
        try
        {
            // create user
            _userService.Create(user, model.Password);
            
            return Ok();
        }
        catch (AppException ex)
        {
            // return error message if there was an exception
            return BadRequest(new { message = ex.Message });
        }
    }

There are a few ways to do what you want.有几种方法可以做你想做的事。 Typically you would take advantage of the wonderful Dependency Injection capabilities built right in to .NET Core and then implement the Repository Pattern .通常,您会利用内置于 .NET Core 的出色的依赖注入功能,然后实施存储库模式

It looks like you are half-way there.看起来你已经成功了一半。

Your controllers should do the bare-minimum (simply calls your DI services) and your services should do all the heavy lifting.你的控制器应该做最低限度的工作(简单地调用你的 DI 服务),你的服务应该做所有的繁重工作。

You have a lot of business logic in your controllers.您的控制器中有很多业务逻辑。 That logic should be abstracted to DI services.该逻辑应该被抽象为 DI 服务。 This way it's easy to share that logic among all your controllers by simply injecting them via controller constructor.这样,只需通过 controller 构造函数注入它们,就可以轻松地在所有控制器之间共享该逻辑。

Typically you don't call one controller in your project from another.通常,您不会在项目中从另一个调用 controller。 If you wanted to do that, you would have to make an actual Http request (using HttpClient ) and that is a waste of resources especially when you have the power of Dependency Injection at your fingertips.如果您想这样做,则必须发出实际的 Http 请求(使用HttpClient ),这是一种资源浪费,尤其是当您拥有触手可及的依赖注入功能时。

The link I provided shows some good examples of what I am talking about, but if you'd like a more specific example, I would be more than happy to provide one.我提供的链接显示了我所说的一些很好的例子,但如果你想要一个更具体的例子,我很乐意提供一个。

I think you just can use call controller.我想你可以打电话给 controller。

OneController.cs OneController.cs

public class OneController : Controller
{
    public IActionResult Index()
    {
        var id = CreateUser();

        TwoController con = new TwoController();
        var returnvalue = con.Register(id);

        return View();
    }

    public int CreateUser()
    {
        return 1;
    }
}

TwoController.cs TwoController.cs

public class TwoController : Controller
{
    public string Register(int id)
    {
        if (id == 1)
            return "Success";
        else
            return "Fail";
    }
}

Result结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从html下拉列表中获取所选项目并将其传递给mvc c#中的另一个控制器 - how to get the selected item from html dropdown list and pass it to another controller in mvc c# 从c#中的另一个Controller从Controller获取值 - Get the value from Controller from another Controller in c# 如何在MVC c#中将HTML选项ID,名称或值从一个视图传递到另一视图的控制器 - how to pass html option id or name or value from one view to another view's controller in MVC c# 如何将 Model 从 controller 传递到另一个 controller - how to pass a Model from a controller to another controller 如何从索引视图传递 id 以创建另一个控制器的方法? - How to pass id from Index View to create method of another Controller? 如何将JSON数据从C#控制器传递到angular js? - How to pass json data from C# controller to angular js? 如何将 integer 列表从 js 传递到 c# controller - How to pass a list of integer from js to c# controller 如何将数据从控制器传递到 C# 中的视图 - How to pass data from controller to the view in C# 如何将对象ID从HTML返回到控制器MVC C# - How to get Object Id from html back to the Controller MVC c# 将日期时间从 javascript 传递给 c#(控制器) - Pass a datetime from javascript to c# (Controller)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM