How to redirect to action in ASP.NET Core WebAPI? - asp.net-core

I've got two actions in my ASP.NET Core Web API application's controller:
[HttpGet("get-all")]
public IActionResult GetAll() { ... }
and
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
...
return RedirectToAction("GetAll");
}
Delete action always redirects to itself and never to GetAll. Why so? In the same time similar redirect from Post action works ok.
Can't find any docs on the subject. Any help?

Have you tried to use RedirectToActionResult? Like this (change ControllerName with your actual Controller's name ):
RedirectToActionResult("GetAll", "ControllerName", null);
Documentation
Hope you'll find this useful.

Related

How does Swagger achieve the same route but different query parameters?

I created an asp.net core web api project, using the .net5 version, and I have a route like this.
[Route("api/detail")]
public IEnumerable<User> Get()
{
//TODO
return users;
}
[Route("api/detail")]
public IEnumerable<User> Get(string name)
{
//TODO
return users;
}
Although my request method is the same and the request parameters are different, the 500 error will be reported in swagger. Is there any way to solve it? Any help is greatly appreciated.
There could be multiple reasons why you're getting a 500 error. When I pasted your code into a new controller the first is error I received was:
Ambiguous HTTP method for action... Actions require an explicit HttpMethod binding for Swagger
It's telling you that you need to decorate each action in the controller with an HttpMethod binding, like [HttpGet]. More on that in a second...
The next issue is that you're using [Route] to bind two different action methods to the exact same route with the same HttpMethod. That's not possible in an API controller.
Conflicting method/path combination... Actions require a unique
method/path combination for Swagger
My preferred method for routing is to use Attribute routing with Http verb attributes.
The first step would be to move the route attribute to the controller. I'm going to assume you've created a DetailsController:
[Route("api/[controller]")]
[ApiController]
public class DetailsController : ControllerBase { }
Now, update your actions. Remove the [Route] attribute, replace with the HttpGet attribute, and add the name parameter to your second endpoint. I also prefer to return an IActionResult:
[HttpGet]
public IActionResult Get()
{
//TODO
return Ok(users);
}
[HttpGet("{name}")]
public IActionResult Get(string name)
{
//TODO
return Ok(users);
}
Note that parameters are identified by using curly braces around the variable {name} in the Http method attribute. Both endpoints work and are accessible through swagger. I urge you to read the linked page above for a better understanding of the possible routing options (linked again).

How to block access to controller via changing Url in ASP.NET Core?

I want to access page when user clicks to button.
By changing url, such as ..../Member/Batch/Create I want my site redirect user to another page.
How can I do this via ASP.NET Core MVC 3.1?
Use:
Create Batch
See this answer and help for more details.
Do you mean we could only access the controller by using button?
If this is your requirement, you could try to check the Request.Headers["Referer"].ToString() to make sure just which url could access this controller.
Like below:
public IActionResult Privacy()
{
var re = Request.Headers["Referer"].ToString();
if (Request.Headers["Referer"].ToString() != "https://localhost:44342/home/index")
{
return View("Error");
}
else
{
return View();
}
}
Result:

Can't use Json() in asp.net core web api as it in asp.net core web

In asp.net core web I create a controller and I can use:
return Json(new {status=true});
but in asp.net core web API I can't do it.
In a controller:
[HttpGet("{id}")]
public JsonResult Get(int id)
{
}
I can not return Json()
How to use it?
Asp.Net Core Web API does provide support for wide varieties of response types, with Json being one among them. You can do that like shown below. Make sure you have all your required dependencies. You can learn about the dependencies from the documentation link I attached in this answer.
[HttpGet]
public IActionResult Get()
{
return Json(model);
}
You can also specify strict response formats using the [Produces] Filter on your controller.
Configuring Custom Formatters
You can also configure your own custom formatters in Asp.Net Web API project by calling the .AddFormatterMappings() from ConfigureServices method inside of your Startup.cs. This allows for a greater control on your content negotiation part and lets you achieve strict restrictions.
Please go through this documentation to understand further.
Using Responses with Status Codes
However, when using Web API, I suggest you use the helper methods that are built in so that your response becomes more expressive as it contains both the response content along with the status code. An example of how to do that is below
[HttpGet]
public ActionResult Get()
{
return Ok(_authors.List());
}
For a full list of helper methods available, you can take a look at the Controller.cs and ControllerBase.cs classes.
Asp.net core web api inherit from controllerBase, which doesn't contain a Json(Object) method. You should initialize a new JsonResult yourself in the action.
[HttpGet("{id}")]
public JsonResult Get(int id)
{
return new JsonResult(new { status = true });
}

Routing is not working for web api with realtions

I am creating web api using asp.net core. The api end point is logically mapped to resource's relations based on guidelines here
So my API looks like
http://tax.mydomain.com/api/v1/clients/1/batches/12/start
Where Client is parent of Batch, 1 is clientid and 12 is batchid, and Start is POST action method.
Here is the corresponding controller
public class TaxController : Controller
{
[HttpPost]
[Route("clients/{clientid}/batches/{batchid}/start")]
public void Start([FromRoute]string clientId, [FromRoute]string batchId,
[FromBody]IEnumerable<string> urls)
{
// do something
}
}
since api/v1 is common to all controllers i configured that in startup's Configure method. Also i want Home as default controller.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvc(routes =>
{
routes.MapRoute("default","api/v1/{controller=Home}/{action=Index}/{id?}");
});
}
However client is getting not found error for api http://tax.mydomain.com/api/v1/clients/1/batches/12/start
Any controller methods that do not have a route attribute use convention-based routing.
When you use [Route] attribute, you define attribute routing and so conventional routing is not used for that action/controller. Therefore, your controller is accessible by
http://tax.mydomain.com/clients/1/batches/12/start
As an option, you can use the fact, that attribute routes can be combined with inheritance. Set a Route attribute on the entire controller and this will work as route prefix (the same behavior as [RoutePrefix] attribute in WebApi):
[Route("api/v1")]
public class TaxController : Controller
{
}
More general example from routing documentation:
[Route("api/[controller]")]
public abstract class MyBaseController : Controller { ... }
public class ProductsController : MyBaseController
{
[HttpGet] // Matches '/api/Products'
public IActionResult List() { ... }
[HttpPost("{id}")] // Matches '/api/Products/{id}'
public IActionResult Edit(int id) { ... }
}
There are two things wrong with your setup
You call http://tax.mydomain.com/clients/1/batches/12/start but you don't have specified the controller name within it. This route looks for a controller named ClientsController. So the correct url would have to be http://tax.mydomain.com/tax/clients/1/batches/12/start instead
You seem to be using default MVC/Viewbased route, but your url suggest you use WebAPI.
When you use WebAPI to create a Rest service, you don't have any actions. Instead, actions map to the Http Verbs (GET (Read), PUT (update/replace), POST (insert), DELETE).
So for REST Services your default route should look like this instead: api/v1/{controller=Home}/{id?}

Checking if the user is logged in asp.net mvc

In my application I am restricting some view and the user has to be logged in to view them. One way would be to check on every action if the user is logged in or not. But after a bit of research I found that asp.net MVS supports some global filter rules.
How do we use them? Ideally I would want to call a filter onBeforeAction and check if the user is logged in or not..
Is this a right approach? If yes, then can any body give me an example?
The easiest way is to add the Authorize attribute to your controller or action methods. For example:
public class MyController : Controller
{
//Normal action
public ActionResult DoSomethingForAnyone() { }
//Secured action
[Authorize]
public ActionResult DoSomethingOnlyForAuthorisedUsers() { }
}
Alternatively you can secure the entire controller and exclude actions you want to be accessible to anonymous users:
[Authorize]
public class SecureController : Controller
{
public ActionResult DoSomething() { }
[AllowAnonymous]
public ActionResult DoSomethingForAnyone() { }
}
Your [Authorize] will not work with the custom login. If you are using Form Authentication or other Authentication method than [Authorize] will work smoothly.
For custom login on success set
FormsAuthentication.SetAuthCookie([user name], false);
This will make your [Authorize] attribute to work properly.
And for logout use below statement
FormsAuthentication.SignOut();
If you follow the above solution than it will reduce your code as well as valid user check on before Action call.