web-api
  1. web-api-working-with-fromuri-attribute

Working with FromUri Attribute - (Web API FromBody and FromUri)

Web API in ASP.NET Core provides two attributes for binding parameters in HTTP requests: FromBody and FromUri. In this tutorial, we'll focus on the FromUri attribute and discuss how to use it to bind parameters from the URI of an HTTP request.

Syntax

The syntax for using the FromUri attribute in an ASP.NET Core Web API action method is as follows:

[HttpGet]
public IActionResult MyAction([FromUri] MyModel model)
{
    // action code here
}

In this example, we're using the FromUri attribute to bind the model parameter from the URI of the HTTP GET request.

Example

Suppose you have the following controller and model defined in your ASP.NET Core Web API project:

public class MyController : Controller
{
    [HttpGet]
    public IActionResult GetItems([FromUri] ItemFilter filter)
    {
        // action code here
    }
}

public class ItemFilter
{
    public int MaxPrice { get; set; }
    public string Category { get; set; }
}

You can then call this action method using a URL that includes query parameters to filter the results:

GET /mycontroller/getitems?maxprice=100&category=books

This URL will bind the MaxPrice and Category properties of the ItemFilter model from the URI parameters.

Explanation

The FromUri attribute is used to bind parameters from the URI of an HTTP request. When used on a parameter in an action method, it tells ASP.NET Core to bind the parameter from the URI parameters, rather than the request body.

By default, ASP.NET Core will only bind simple types like strings and integers from URI parameters. If you want to bind more complex types like models, you need to use the FromUri attribute to tell ASP.NET Core to bind the model from the URI parameters.

Use

The FromUri attribute is useful when you need to provide input to your Web API action methods through the URI of an HTTP request. This is commonly used in scenarios where you need to filter or search for data based on user input.

Important Points

Here are some important points to keep in mind when using the FromUri attribute in ASP.NET Core:

  • By default, ASP.NET Core only binds simple types from URI parameters.
  • To bind more complex types like models from URI parameters, you need to use the FromUri attribute.
  • Always validate user input to avoid security vulnerabilities.

Summary

In this tutorial, we discussed the FromUri attribute in ASP.NET Core Web API, which allows you to bind parameters from the URI of an HTTP request. We covered syntax, example, explanation, use, and important points of using the FromUri attribute to bind complex types like models from URI parameters. By using the FromUri attribute in your ASP.NET Core Web API project, you can provide users with an easy way to filter or search for data through the URI of an HTTP request.

Published on: