Structure of asp.net with web api and mvc controller - c#

I have a question about the structure of asp.net website, especially back-end stuff
Currently, I have sql database, web api controller and mvc controller.
I have been using web api for getting or posting data to database, and using mvc controller for directing webpage.
What I want to do is as followings
It is basically registration process
call web api method to post user email and password from mvc controller
web api controller processes the user email and password, using stored procedures and functions
if the user email already exists in the database, web api returns some custom status code? to let the mvc controller know that.
Here is problem, since the web api will be used by other devices as well so I can't directly do some business logic for dealing with the duplication of email. So I just want to let somehow the MVC controller know the error and do some business logic.
How can I do that?, Is it fine to return some status code like 101, 201 to MVC controller? then How can I do that??
Thanks guys

Use standard HttpResponse with a code from public enum HttpStatusCode
Under the link you'll find the list of all codes and some examples how to use and consume them;
for example, in your API controller may return:
return new HttpResponseMessage(HttpStatusCode.NotAcceptable);
and then on the consumer side you'll have to handle that error.

Related

ASP.NET Core MVC/WebAPI Authentication Schemes plus Anonymous

I'm having an issue with a website plus API I'm writing. These are in the same project, if that matters.
Reduced to its simplest form, it's a catalogue website and API. You have products in a database and pages which display product information. You also have other pages which allow editing this information and adding new products, etc.
There are three ways you can do this:
Anonymous users can list products and view public information about them on the website.
Signed-in users can list, view (including private info), edit, create and delete products on the website.
Users with a valid API key can list, view (including private info), edit, create and delete products using the API.
The problem I'm having is that the website uses AJAX calls to the API, and these only work if the user of the website is authenticated. Calling the API without an authentication cookie or an API key fails by design.
What would be the recommended way of identifying the unauthenticated website to the back-end API in a secure way that allows it to work?
The ideas I've had include:
A special API key for the website, but it would by necessity be visible to the world at large somewhere in the Javascript code and therefore something someone could use to access the API themselves and bypass any rate limiting I wanted to implement.
I considered setting something in the session on the web controllers which could then be verified in the API controllers, but I encountered issues where unauthenticated calls to the API redirect to the login page on the Account controller, which then sets the relevant session variable, which means subsequent API calls succeed whether legitimately authenticated or not. This seems like the most promising option, but I'm not familiar enough with ASP.NET Core's workings to make it robust.
You should use Jason Web Token Authentication, to implement one in your API please check the following the link:
https://medium.com/#adegokesimi/implementing-jwt-and-refresh-token-in-net-core-2-2-web-api-b21ef6de2a19
By using JWT authentication in the pipe line of your WebApi your problem will be solved.
Also, you can use a ASP.NET Core identity system for things like roles that can be implemented on specific controller methods, for example, "EDIT" can be allowed only to role admin, etc.
Kind regards,
.js

Getting 404 when trying to hit the WebAPI controller method

I have created a project using ASP.NET Core Web Application (.NET Framework). My project structure:
My values controller is inherited from an MVC controller. When I hit http://localhost:20798/api/values, I do get the desired response.
I added ConsumerScore controller, this time a WebAPI controller inheriting from ApiController. But now when I hit http://localhost:20798/api/consumerscore, I am getting 404 response.
My ConsumerScore controller looks like:
How to resolve this error?
The error is with the "ApiController" you should use just Controller in your implementation.
There is indeed to particular ApiController class anymore since MVC and WebAPI have been merged in ASP.NET Core. However, the Controller class of MVC brings in a bunch of features you probably won't need when developing just a Web API, such as a views and model binding.
for more see: Is ApiController deprecated in .NET CORE?
Seems like you are confusing the idea of "MVC" and "Web API".
ASP.net MVC is used for serving web pages while the Web API is supposed to be serving data in a negotiable way (json/xml/...) to http requests.
Adding an "api/*" to an MVC route and serving data from an MVC Controller is not the best idea and will not turn it into a useful web service.
From the look of your methods, I suppose what you need is an ApiController but you cannot create the http request by copying the "~/api/*" to your web browser and you need to use tools like fiddler or your browser's debugger.

How do I pass auth tokens around for temporary Web API access in MVC6?

I'm building a website that has an API service that dumb clients use to get and submit data. I'm building it using ASP.NET MVC6 and EF7.
The service is still in a prototyping stage, however I'm currently using the [Authorize] attribute on controller classes and methods and the default User Manager found in the MVC6 template (ASP.NET Identity?). It works pretty well for the website itself and for the purposes for the prototype and testing I've simply put [AllowAnonymous] attribute on the API methods that I need to access from the unauthorized machines.
However I think I need to basically pass a session token to these dumb clients that last only x hours that they can use to submit with GET and POST requests so they can be pre-authorized without having to pass around some master user/pass.
Note: I'm fairly new to MVC6 and do not have full knowledge of how ASP.NET / MVC security is handled.

Send data from web API controller into separate asp.net mvc website

I have the following situation:
There are two different projects in our solution:
asp.net mvc website
asp.net web api (service for mobile apps).
Users should have an ability to upload profile pictures from their mobile apps using mobile web api project. But the problem is that images are physically stored on different server at asp.net mvc website.
So here is the flow:
User uploads picture and sends it to mobileapidomain/api/user/uploadpicture. (base64)
Now I have to send this image to asp.net mvc site and store it on asp.net mvc server.
What is the best way to send current base64 string with image from web api controller into asp.net mvc project?
In such situation I think the best option would be to install within your mvc web application project packages for WebApi and make this project web application (normal usage) and web service at the same time. Then create new ApiController like this:
[HttpPost]
public IHttpActionResult UploadPicture(string base64)
{
// Do something with image
return Ok();
}
If you do not wish to install WebApi libraries there then I would suggest adding new regular Controller for uploading pictures and adding there similar action:
[HttpPost]
public void UploadPicture(string base64)
{
// Do something with image
}
If something goes wrong within the acton throw exception to inform peer that something wrong is going on. If the file is too long to send in one post I would suggest splitting it and concatenating within mvc application as it receives new portions of it.

Implementing authentication in ASP.Net Web API

I am aware this is the most basic question and is asked many times, however I have failed to find relevant details for my requirement.
I am developing ASP.Net as front end and using ASP.Net Web API service. I am planning to use Basic Auth using SSL.
Could someone help me with below:
In future, I plan to have multiple clients including Android, iOS and Windows phone client. Any issues using Basic Auth over SSL?
Please help me confirm if below is right implementation approach.
I will write new Controller - AccountController in ASP.net Web API and use this controller for methods: Login, Logout and RegisterNewUser. All of them will be POST methods.
What should be code inside Login API apart from verifying user from database. Also should login method return any object to client?
Any reference which will help me understand client side of code, which will send authorization token on every web api request? Note: I am heavily using jqGrid with CRUD operation, which will make API requests.
There are no problems using Basic Authentication using these clients as far as I know. I have tested this scenario with Android myself.
I have just successfully implemented Basic Auth using this link as a resource:
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers
/Rune
1) There's no problem using SSL and Basic Auth together.
2/3/4) That would be a valid approach, though I'd recommend that you create a new MVC project and look at the generated code in the AccountController.cs file. This will give you some guidance on how to code these actions.

Categories