How to create an attribute that serve as a Web API? - c#

I am working on a project that we need to shift the responsibility of authorization level to the separated Web API.
What is important creating an attribute class in Web API which able to check some policies. What we want is adding the Web API reference to other projects and check these policies by adding AuthPolicyAttribute above actions and controllers. By adding this attribute, Web API check accessibility by getting the action name and user name.
For example (This is one of the actions in a project that need to call Web API by AuthPolicy attribute):
[AuthPolicy]
public IActionResult GetTypes([FromBody]Input input)
{
// Code
}
I've searched a lot but unfortunately, I haven't found any example.

Related

Create an api for existing web application in ASP.NET Core

I have 2 separate projects:
Web API
Web application (GUI)
Both will have the same logic and code, it's just their return type that are different.
Obviously the API will return json, and the web app will have views.
My question: is there a way to use the same controllers and actions for both web app and api? I just don't want to repeat myself and use less code.
What I have found is that you can have multiple routes for your controller, and then you can get the current url in your controller.
So something like:
[Route("api/[controller]")]
[Route("[controller]")]
class MyController:ControllerBase
{
[HttpGet]
public IActionResult Hi()
{
// if (url startwith "api")
//return json
//otherwise return some view
}
}
I didn't try myself because I wasn't sure if this was a right way to solve it or not, and on the other hand I have to put that if check in all the methods...
Since you have two different projects so you have to use different controllers and actions. You cannot use same physical controllers and actions from two different projects.

how does web api attribute tag work

new to c sharp, visual studio and web api. (come from java).
Anyways I'm playing around with web api from visual studio. In the ValuesControler class I notice it set something call a attribute on top of the class, so whenever a browser make a request to api/values it will need to be authorized first.
But what exactly is an attribute?
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
I also found the routing attributes, but I cant find any info on what exactly is attributes and how is it getting read or understood by the program.
In c# Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
For authorize attribute check out
Authentication and Authorization in ASP.NET Web API
Using the [Authorize] Attribute
Web API provides a built-in authorization filter, AuthorizeAttribute.
This filter checks whether the user is authenticated. If not, it
returns HTTP status code 401 (Unauthorized), without invoking the
action.
For attribute routing check out
Attribute Routing in ASP.NET Web API 2
Routing is how Web API matches a URI to an action. Web API 2 supports
a new type of routing, called attribute routing. As the name implies,
attribute routing uses attributes to define routes. Attribute routing
gives you more control over the URIs in your web API. For example, you
can easily create URIs that describe hierarchies of resources.

Enable CORS in Umbraco 6 / Web API 2 Instance

I'm a newer developer who has been developing a RESTful API with Web API 2 within an instance of Umbraco 6. After some research on http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api, I added the attribute to my controller as such:
[EnableCors(origins: "http://example.com,http://example.local", headers: "*", methods: "*")] //CORS TESTING
public class PropertiesController : UmbracoApiController
{
//Code Hidden
}
I'm finding that I can go to a site like http://codebeautify.org/jsonvalidate and pull in my JSON through the endpoint URL and validate it even though I didn't allow that host to call my API.
Following the instructions from the asp.net link above, I noticed that my solution doesn't have an "App_Start" folder with a WebApiConfig.CS file, so I was never able to add the config.EnableCors(); code which I think may be the underlying issue? I'm not sure how to continue at this point because to get this far, I just had to add a new Web API Controller Class to '/App_Code' and then inherit UmbracoApiController.
You can create the WebApiConfig.cs if you wish and call it from Global.asax.cs . Or just call EnableCors() wherever you have the config. This is a simple answer with an example https://stackoverflow.com/a/29397652/3520146 .

MVC Web Api as a middle tier service

In our recent application we are planning to use MVC Web API as a Middler tier service. Meaning, front end will access the WebAPI middler tier service to get all the data it required from DB and to update the data back to DB. Along with this there may be many other methods that we will need. For example check whether user already exists in the system, Validate the address, etc. Now I have come into a point that my webapiconfig.cs routing is becoming more complex. For example my UserController in WebApi project will have following methods.
public User Get(int userId)
{
}
public bool IsUserExists(string username)
{
}
public bool UpdateUser([FromBody]User user)
{
}
public bool ChangePassword(string username, string password)
{
}
To manage all of these I may need so many routing configurations in webapiconfig.cs. I am not sure how to deal with these when other controllers comes to the picture. Should I use AttributeRouting? Any suggestion highly appreciated. Thanks.
If you have the option to use web api 2 go for attribute routing. You can save your lot of development effort in configuring routes.
Also make sure you are following resource based routing design and REST principles, than old RPC style routes. i.e for basic CRUD operations :-
Create - HTTP POST to /user
Read - HTTP GET to /user or /user/{id}
Update - HTTP PUT to /user
Delete - HTTP DELETE to /user/{id}
For example for updating an user
Instead of route /user/UpdateUser
You should do a
HTTPPUT to /user/
For more tips on REST check this.

Is it possible for ASP.NET MVC website (not project) to return HttpResponseMessage

I am creating a RESTful webservice using ASP.NET MVC (not ASP.NET Web API). What I want to do is have every method in the controller return their result based on an input parameter (i.e. json or xml).
If I were using ASP.NET Web API, the HttpResponseMessage works for this purpose. When I attempt to return an HttpResponseMessage from a controller in ASP.NET MVC, there is no detail.
I have read that in this approach, I am supposed to use ActionResult. If I do this, then I need to create an XmlResult that inherits from ActionResult since it is not supported.
My question is why HttpResponseMessage does not work the same in both situations. I understand that in Web API, we inherit from ApiController and in ASP.NET MVC we inherit from System.Web.Mvc.Controller.
Any help is greatly appreciated.
Thanks,
EDIT 1
Much thanks to Fals for his input. My problem was in how to create an empty website and add all of the necessary functionality in. The solution was to use Nuget to get the packages mentioned in the comments and then to follow the steps in How to integrate asp.net mvc to Web Site Project.
Web Api is a Framework to develop Restfull services, based on HTTP. This framework was separeted into another assembly System.Web.Http, so you can host it everywhere, not only in IIS. Web API works directly with HTTP Request / Response, then every controller inherit from IHttpController.
Getting Started with ASP.NET Web API
MVC has It's implementation on System.Web.Mvc. coupled with the ASP.NET Framework, then you must use It inside an Web Application. Every MVC controller inherits from IController that makes an abstraction layer between you and the real HttpRequest.
You can still access the request using HttpContext.Response directly in your MVC controller, or as you said, inheriting a new ActionResult to do the job, for example:
public class NotFoundActionResult : ActionResult
{
private string _viewName;
public NotFoundActionResult()
{
}
public NotFoundActionResult(string viewName)
{
_viewName = viewName;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 404;
context.HttpContext.Response.TrySkipIisCustomErrors = true;
new ViewResult { ViewName = string.IsNullOrEmpty(_viewName) ? "Error" : _viewName}.ExecuteResult(context);
}
}
This ActionResult has the meaning of respond thought HTTP Error.
As a matter of fact, it is indeed possible. You basically have two options:
develop your custom ActionResult types, which can be an heavy-lifting work and also quite hard to mantain.
add WebAPI support to your website.
I suggest you to do the latter, so you will have the best of two worlds. To do that, you should do the following:
Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
Add one or more ApiControllers to your /Controllers/ folder.
Add a WebApiConfig.cs file to your /App_Config/ folder where you can define your Web API routing scheme and also register that class within Global.asax.cs (or Startup.cs) file.
The whole procedure is fully explained here: the various steps, together with their pros-cons and various alternatives you can take depending on your specific scenario, are documented in this post on my blog.

Categories

Resources