How to call controller method from async Task<IActionResult> method? - asp.net-core

I want to call normal action method from my another method,but debugger does not go to that method.
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
//Code Logic
return RedirectToAction("SecondMethod");
}
public IActionResult SecondMethod()
{
return View();
}

If you only want to redirect, this code will work.
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
//Code Logic
return RedirectToAction("SecondMethod","YourControllerName");
}
public IActionResult SecondMethod()
{
return View();
}
Nothing special here, you just want to redirect to SecondMethod once the UploadFile is finished.
But you can't invoke it as a method since it uses IActionResult what IActionResult does is it defines a contract that represents the result of an action method.

RedirectToAction results in a redirect being sent to the client's browser, which then has to request the URI being redirected to.
So calling return RedirectToAction("SecondMethod"); will not invoke SecondMethod in and of itself, it depends on whether the client follows the redirect.

Related

In Asp Net Core, Do I have to put the Attribute of [Authorize] for both Get and Post Method?

In the controller, normally we have a Get and a Post methods
for example:
[HttpGet]
[Authorize(Policy = "AdminMs")]
public async Task<IActionResult> MSCreate()
{
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Policy = "AdminMs")]
public async Task<IActionResult> MSCreate(empolyee)
{
}
Do I have to set the Authorize Attribute for both methods or only for HttpGet?
If you need only authorized access to any of the end points, you have to use [Authorize] on whichever method that corresponds to that endpoint. Having it on one method does not mean that it will restrict the other method even if they have similar method names.

How to remove value from route int .net core

I'm writing .net core mvc app. I have two methods
[HttpGet("{action}/{userId}")]
public async Task<IActionResult> ChangeUser(string userId)
{
var user = await _dbContext.Users.Where(x => x.Id == userId).FirstOrDefaultAsync();
...
return View(new ChangeUserVM());
}
[HttpPost("{action}/{userId}")]
public async Task<IActionResult> ChangeUser(ChangeUserVM user)
{
...
}
I need routing in the HttpGet method to get into the first method. But then i want to get from the html to the second method and i have to use routing again otherwise i get 405. How i can get rid of routing in the second method?
I can’t verify my suggestion right now, but over second method, try to remove from HttpPost attribute “userId”.
[HttpPost(“action”)]
public async Task<IActionResult> ChangeUser(ChangeUserVM user)

Is it possible to restrict an action method to "only redirect-to access"?

Using ASP.NET Core 3.1 - MVC, I have an HTTP Post action method that gets data from a client and works on database. Because this action method was very long and untidy and many repeated codes, I decided to simplify this action method and use Redirect-to. Something like this :
[HttpPost]
[ValidateAntiForgeryToken]
[Route("MainActionMethod")]
public async Task<IActionResult> MainActionMethod([FromBody]object jsonData)
{
. . .
if (condition a)
return RedirectToAction("Action1");
if (condition b)
return RedirectToAction("Action2");
. . .
}
Action1 must be HTTPGet to be redirected and so a user can type a URL like this and modify my database
http://www.example.com/?param1="Hello"&param2="Stacky"
How could I disable access to HTTP GET Action1 from the browser and be accessed only from other action methods or only by redirect-to?
There is an attribute Referer in the header of Request. If it is accessed from a browser, its value is empty. Use this to determine the subsequent processing procedure.
[HttpPost]
[ValidateAntiForgeryToken]
[Route("MainActionMethod")]
public async Task<IActionResult> MainActionMethod([FromBody]object jsonData)
{
if (true)
return RedirectToAction("Action1");
}
public IActionResult Action1()
{
StringValues header ;
Request.Headers.TryGetValue("Referer",out header);
if (header.Count==0)
{
return BadRequest();
}
return Ok("Action1");
}

Unable to configure route for Get in WebApi 2

I'm struggling with something very basic. I'm trying to be get a response from my WebApi2 restful service, and I can't.
I have not edited the default WebApi (WebApiConfig.cs) route.
This is the controller
public class AboutController
{
[Route("api/about/{id:int}/{service1}/{service2}")]
public async Task<IHttpActionResult> Get(int accountId, string mainservice, string secondaryservice)
{
//logic
}
}
If I navigate (in a browser) to http://localhost:58090/api/about I get the error message The requested resource does not support http method 'GET'. I guess this makes sense, as it doesn't match the route (path).
If I update the path to something which matches the signature, such as http://localhost:58090/api/about/1/a/b I get the error message No action was found on the controller About' that matches the request.
Even if I add [HttpGet] to the controller, it makes no difference.
As a sanity test, I updated to
public class AboutController
{
public async Task<IHttpActionResult> Get()
{
//logic
}
}
and it does what is expected. I'm lost as to why adding the parameters has confused things so much.
I'm lost as to what I've done wrong
The route must match the parameters
[Route("api/about/{id:int}/{service1}/{service2}")]
public async Task<IHttpActionResult> Get(int id, string mainService, string secondaryService)
{
The above won't work, because it is expecting to see service1 and service2 based upon the route.
Update as per the example below
[Route("api/about/{id:int}/{service1}/{service2}")]
public async Task<IHttpActionResult> Get(int id, string service1, string service2)
{

Make All Controller Methods Asynchronous

Right now I have a method in my controller that just returns a static page.
public IActionResult CookiesPolicy()
{
return View();
}
All my other controller methods are asynchronous and I would also like to make this method asynchronous. Can I do this? And if not, why not?
public async Task<IActionResult> CookiesPolicy()
{
return View();
}
Edit: If I do this Visual Studio tells me the method lacks await operators and will run synchronously.
public async Task<IActionResult> CookiesPolicy()
{
return await Task.FromResult(View());
}
But this doesn't really make your program better.