In Asp.Net Core there are 7 HttpMethod attributes by default: (HttpDelete, HttpGet, HttpPost, HttpPut, HttpOption, HttpPatch, HttpHead).
In this article, we want to create two custom attributes called HttpRead and HttpWrite that use HttpWrite for requests that do write operations and HttpRead for requests that do only read operations. To create an HttpMethod attribute, you must create a class that inherits from the HttpMethodAttribute.
public class HttpReadAttribute : HttpMethodAttribute
{
private static readonly IEnumerable<string> _supportedMethods = new[] { "READ" };
public HttpReadAttribute()
: base(_supportedMethods)
{
}
public HttpReadAttribute(string template)
: base(_supportedMethods, template)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
}
}
You must enter a list of acceptable words for this Attribute in the constructor of this class. For example, in the created attribute, only the word READ is accepted, which means that if this attribute is placed on an action, it will only accept requests whose HttpMethod is of type READ. Then we have to put this attribute on the desired action:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpRead]
public IActionResult Read()
{
string result = "Read api";
return Ok(result);
}
[HttpWrite]
public IActionResult Write()
{
string result = "Write api";
return Ok(result);
}
}
Now if you enter the api/values address in the browser, you will not receive any data, but if you can specify HttpMethod and set HttpMethod to Read via Postman or any other program you can send a request to the Read action, otherwise, You will receive a 405 response.
HttpWrite Code:
public class HttpWriteAttribute : HttpMethodAttribute
{
private static readonly IEnumerable<string> _supportedMethods = new[] { "WRITE" };
public HttpWriteAttribute()
: base(_supportedMethods)
{
}
public HttpWriteAttribute(string template)
: base(_supportedMethods, template)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
}
}
;)
Powered by Froala Editor