简体   繁体   中英

How to redirect to the post overload of an IActionResult

I'm working on an Apsp.Net 6 project targeted .Net6 .

I have this ActionResult:

    [Route( nameof(Recreate))]
    public async Task<IActionResult> Recreate()
    {
       //Some code here
    }

    [HttpPost]
    [Route( nameof(Recreate))]
    public async Task<IActionResult> Recreate(StudentYearlyResultReCreateVm model)
    {
       //Some code here
    }

Now I have another ActionResult described like this:

    [Route( nameof(RecreateWithId))]
    public async Task<IActionResult> RecreateWithId(int id)
    {
        var result = await _studentYearlyResultRepository.GetByIdAsync( id );
        var modelObj = new StudentYearlyResultReCreateVm() {StudentId = result.StudentId , AcademicYearId = result.AcademicYearId};

        return RedirectToAction( nameof( Recreate ) , modelObj );
    }

The problem: The problem is in RecreateWithId method I try to RedirectToAction to the post overload for Recreate action, but all I got is just redirected to the Get one.

So please how I can redirect to the post overload of Recreate ? Thank you in advance.

When you return an action using RedirectToAction , the server returns a 3xx Response to browser with Location header to that Url. Browser then proceeds to access that URL with GET verb, there is no way to change this unless you use Javascript to submit a form from that GET Url.

As for your question, I think a good solution should separation of concern by having a Service for processing:


[Route("api")]
public class ApiController
{

    ApiService service;
    public ApiController(ApiService service)
    {
        this.service = service;
    }

    [HttpGet, Route("")]
    public async Task OnGetAsync()
    {
        await this.service.DoSomethingAsync();
    }

    [HttpPost, Route("")]
    public async Task<IActionResult> OnPostAsync()
    {
        await this.service.DoSomethingElseAsync();

        // If you call this, don't redirect or it may call DoSomethingAsync twice
        await this.service.DoSomethingAsync();
        
        return this.RedirectToAction(nameof("OnGetAsync"));
    }

}

A quick, maybe dirty(?), solution.

[Route( nameof(RecreateWithId))]
public async Task<IActionResult> RecreateWithId(int id)
{
    var result = await _studentYearlyResultRepository.GetByIdAsync( id );
    var modelObj = new StudentYearlyResultReCreateVm() {StudentId = result.StudentId , AcademicYearId = result.AcademicYearId};

    return await Recreate(modelObj );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM